32

我在 C# WPF 应用程序中有一个图像,其构建操作设置为“资源”。它只是源目录中的一个文件,尚未通过拖放属性对话框添加到应用程序的资源集合中。我正在尝试将其编写为流,但尽管尝试了很多点、斜线、名称空间和其他所有内容,但我无法打开它。

我可以使用“pack://application:,,,/Resources/images/flags/tr.png”在 xaml 中的其他地方访问它以使用它,但我无法访问包含它的流。

大多数地方似乎都说使用

using(BinaryReader reader = new BinaryReader(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("ResourceBlenderExpress.Resources.images.flags.tr.png"))) {
    using(BinaryWriter writer = new BinaryWriter(File.OpenWrite(imageFile))) {
        while((read = reader.Read(buffer, 0, buffer.Length)) > 0) {
            writer.Write(buffer, 0, read);
        }
        writer.Close();
    }
    reader.Close();
}

我没有任何运气。

4

4 回答 4

34

您可能正在寻找Application.GetResourceStream

StreamResourceInfo sri = Application.GetResourceStream(new Uri("Images/foo.png"));
if (sri != null)
{
    using (Stream s = sri.Stream)
    {
        // Do something with the stream...
    }
}
于 2009-09-07T08:06:21.363 回答
29

GetManifestResourceStream 用于传统的 .NET 资源,即那些在 RESX 文件中引用的资源。这些与 WPF 资源不同,即通过 Resource 的构建操作添加的资源。要访问这些,您应该使用Application.GetResourceStream,并传入适当的 pack: URI。这将返回一个 StreamResourceInfo 对象,该对象具有用于访问资源数据的 Stream 属性。

于 2009-09-07T08:10:18.230 回答
8

如果我没听错,您在打开资源流时遇到问题,因为您不知道它的确切名称?如果是这样,你可以使用

System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceNames()

获取所有包含资源的名称列表。这样您就可以找到分配给您的图像的资源名称。

于 2009-09-07T08:02:38.323 回答
-1

无需调用 Close() 方法,Dispose() 在 using 子句结束时会自动调用该方法。因此,您的代码可能如下所示:

using(BinaryReader reader = new BinaryReader(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("ResourceBlenderExpress.Resources.images.flags.tr.png")))
using(BinaryWriter writer = new BinaryWriter(File.OpenWrite(imageFile))) 
{
    while((read = reader.Read(buffer, 0, buffer.Length)) > 0) 
    {
        writer.Write(buffer, 0, read);
    }
}
于 2009-09-07T07:49:23.593 回答