Resource from assembly as a stream

前端 未结 4 1402
予麋鹿
予麋鹿 2020-12-05 02:43

I have an image in a C# WPF app whose build action is set to \'Resource\'. It\'s just a file in the source directory, it hasn\'t been added to the app\'s resource collection

相关标签:
4条回答
  • 2020-12-05 03:00

    GetManifestResourceStream is for traditional .NET resources i.e. those referenced in RESX files. These are not the same as WPF resources i.e. those added with a build action of Resource. To access these you should use Application.GetResourceStream, passing in the appropriate pack: URI. This returns a StreamResourceInfo object, which has a Stream property to access the resource's data.

    0 讨论(0)
  • 2020-12-05 03:10

    There's no need to call the Close() method, it will be automatically called by Dispose() at the end of the using clause. So your code might look like this:

    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);
        }
    }
    
    0 讨论(0)
  • 2020-12-05 03:16

    If I get you right, you have a problem to open the resource stream, because you do not know its exact name? If so, you could use

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

    to get a list of names of all included resources. This way you can find the resource name that was assignd to your image.

    0 讨论(0)
  • 2020-12-05 03:23

    You're probably looking for Application.GetResourceStream

    StreamResourceInfo sri = Application.GetResourceStream(new Uri("Images/foo.png"));
    if (sri != null)
    {
        using (Stream s = sri.Stream)
        {
            // Do something with the stream...
        }
    }
    
    0 讨论(0)
提交回复
热议问题