【问题标题】:Resource from assembly as a stream来自程序集的资源作为流
【发布时间】:2023-03-20 13:06:01
【问题描述】:

我在 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();
}

我没有运气。

【问题讨论】:

    标签: c# wpf embedded-resource


    【解决方案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);
        }
    }
    

    【讨论】:

    • 这如何回答这个问题?
    • 真的吗?有用的见解,如果它是真的。我一直认为明确调用 Close 对流/文件更好。
    • Using语句的使用是显式调用Stream的dispose方法,隐式调用它的Close方法。此外,即使引发异常,using 语句也始终处理“已使用”对象,因此 using 是一个包罗万象、几乎没有错误的语句。
    【解决方案2】:

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

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

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

    【讨论】:

    • 为什么不用GetCallingAssembly 而不是GetExecutingAssembly
    • Application.ResourceAssembly 可能是获取包含应用程序资源的程序集的首选方式。此外,这个答案适用于 resx 文件,而不是 WPF 资源文件,这就是这个问题的意义所在。
    【解决方案3】:

    您可能正在寻找Application.GetResourceStream

    StreamResourceInfo sri = Application.GetResourceStream(new Uri("Images/foo.png"));
    if (sri != null)
    {
        using (Stream s = sri.Stream)
        {
            // Do something with the stream...
        }
    }
    

    【讨论】:

    【解决方案4】:

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

    【讨论】:

      猜你喜欢
      • 2021-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多