我目前正在开发一个卡片 DLL,其中我需要将每张卡片的图像文件作为嵌入式资源,当前项目如下所示:
注意:卡片图像 (.png) 位于 Resources 文件夹中。
我一直在尝试的代码几乎是我能找到的唯一代码,是这样的:
Assembly _assembly;
Stream _imageStream;
private Image img;
public Image Img
{
get
{
return img;
}
}
public Kaart() : this(5, "Spades") { }
public Kaart(int val, string s)
{
this.KaartWaarde = val;
this.Figuur = s;
this._imageStream = imgS();
this.img = new Image(_imageStream);
}
private Stream imgS()
{
try
{
_assembly = Assembly.GetExecutingAssembly();
Stream s = _assembly.GetManifestResourceStream(string.Format("{0}{1}.png", this.kaartWaarde, this.figuur.Substring(0, 1)));
if (s != null)
return s;
else
return null ;
}
catch
{
throw new Exception("Kaart kan niet geladen worden.");
}
}
我似乎得到的唯一异常是在创建 Kaart
对象时的异常,代码在这里:
Kaart k = null;
try
{
k = new Kaart();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message); //This MessageBox is being shown
}
ImageSourceConverter c = new ImageSourceConverter();
testBox.Source = (ImageSource)c.ConvertFrom(k.Img);
使用MessageBox捕获并显示的异常如下:
Value of 'null' is not valid for 'stream'.
在代码执行期间观察我的变量时,我不知何故注意到了这条线
Stream s = _assembly.GetManifestResourceStream(string.Format("{0}{1}.png", this.kaartWaarde, this.figuur.Substring(0, 1)));
无法找到图像,即使使用 Kaarten.{0}{1}.png
这让我怀疑我是不是做错了什么,还是使用了错误的语法。有什么想法吗?
编辑:
图像现在正在正确加载,但是 ImageSourceConverter 仍然抛出 NullReferenceException
据我所知,卡片创建和加载 Stream
对象(并将它们卸载到 Image
对象中)现在工作正常,但是当尝试实际显示时使用下面的代码在我的 WPF Image 控件中的图像,抛出 NullRefException。
Kaartspel kaarten = new Kaartspel();
Kaart k = kaarten.kaarten[7];
ImageSourceConverter c = new ImageSourceConverter();
testBox.Source = (ImageSource)c.ConvertFrom(k.Img); //Exception here
最佳答案
要获取资源,您应该使用 GetManifestResourceStream(string)
和区分大小写的合格资源名称,该名称由两个点分隔的部分组成:
- 包含资源的项目的默认命名空间。在大多数情况下,默认命名空间等于项目名称。
- 资源文件名,包括项目的相对路径。所有目录分隔符都必须用点代替。
resource_name ::= default_namespace '.' full_file_name
full_file_name ::= (directory_name '.')* file_name
在你的情况下:
string name = string.Format("Kaarten.Resources.{0}{1}.png", this.kaartWaarde, this.figuur.Substring(0, 1)));
Stream stream = _assembly.GetManifestResourceStream(name);
获取资源的另一种方法是使用 GetManifestResourceStream(Type, string)
。在这种情况下,名称是相对于指定类型的命名空间( MSDN ,请参阅备注)。
string name = string.Format("Resources.{0}{1}.png", this.kaartWaarde, this.figuur.Substring(0, 1)));
Stream stream = _assembly.GetManifestResourceStream(typeof(Kaart), name);
关于c# - 无法使用 GetManifestResourceStream 找到嵌入式资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30006530/