错误:'null'的值对'stream'无效

时间:2013-10-26 11:33:36

标签: c# winforms

我打开了 WinForms应用程序项目的<{1}}文件并在那里复制了图像。我使用下面显示的代码从资源中获取图像,但收到以下错误:

  

'null'的值对'stream'无效。

此行发生错误:

Resources.resx

相关代码:

btn.BackgroundImage = new Bitmap(
  System.Reflection.Assembly.GetEntryAssembly().GetManifestResourceStream(test));

private void genericButton_event(object sender, EventArgs e) { var btn = (Button)sender; string test = "StudentModule.Properties.Resources" + btn.Name + ".png"; //Getting the error here: btn.BackgroundImage = new Bitmap(System .Reflection .Assembly .GetEntryAssembly() .GetManifestResourceStream(test)); } 的值为test,但我认为它应该是:"StudentModule.Properties.ResourcesbtnAbout.png"。我也尝试了这条线,但它不起作用:

"StudentModule.Properties.Resources.btnAbout.png"

我在这里做的错误是什么?

1 个答案:

答案 0 :(得分:4)

当无法找到流时,GetManifestResourceStream()返回null。然后它将轰炸Bitmap构造函数。

所以你使用的字符串是错误的。目前尚不清楚您是如何嵌入资源的。强烈建议使用资源设计器Project + Resources选项卡。单击“添加资源”按钮上的箭头,选择“添加现有文件”,然后选择该文件。然后,您可以使用ResourceManager获取位图:

var imageName = "Chrysanthemum";
btn.BackgroundImage = (Bitmap)Properties.Resources.ResourceManager.GetObject(imageName);

请注意资源名称只是资源设计器中显示的普通资源名称。

相关问题