Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
967 views
in Technique[技术] by (71.8m points)

c# - How to Read an embedded resource as array of bytes without writing it to disk?

In my application I compile another program from source.cs file using CodeDom.Compiler and I embed some resources ( exe and dll files ) at compile time using :

 // .... rest of code

if (provider.Supports(GeneratorSupport.Resources))
{
    cp.EmbeddedResources.Add("MyFile.exe");
}
if (provider.Supports(GeneratorSupport.Resources))
{
    cp.EmbeddedResources.Add("New.dll");
}
// ....rest of code 

In the compiled file, I need to read the embedded resources as array of bytes. Now I'm doing that by extracting the resources to disk using the function below and the use

File.ReadAllBytes("extractedfile.exe");
File.ReadAllBytes("extracteddll.dll");

I do this after extracting the two files to disk using this function :

public static void ExtractSaveResource(String filename, String location)
{
    //  Assembly assembly = Assembly.GetExecutingAssembly();
    System.Reflection.Assembly a = System.Reflection.Assembly.GetExecutingAssembly();
    // Stream stream = assembly.GetManifestResourceStream("Installer.Properties.mydll.dll"); // or whatever 
    // string my_namespace = a.GetName().Name.ToString();
    Stream resFilestream = a.GetManifestResourceStream(filename);
    if (resFilestream != null)
    {
        BinaryReader br = new BinaryReader(resFilestream);
        FileStream fs = new FileStream(location, FileMode.Create); // say 
        BinaryWriter bw = new BinaryWriter(fs);
        byte[] ba = new byte[resFilestream.Length];
        resFilestream.Read(ba, 0, ba.Length);
        bw.Write(ba);
        br.Close();
        bw.Close();
        resFilestream.Close();
    }
    // this.Close(); 
}

How can I do the same thing (Get the embedded resources as array of bytes) but without writing anything to hard disk?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are actually already reading the stream to a byte array, why not just stop there?

public static byte[] ExtractResource(String filename)
{
    System.Reflection.Assembly a = System.Reflection.Assembly.GetExecutingAssembly();
    using (Stream resFilestream = a.GetManifestResourceStream(filename))
    {
        if (resFilestream == null) return null;
        byte[] ba = new byte[resFilestream.Length];
        resFilestream.Read(ba, 0, ba.Length);
        return ba;
    }
}

edit: See comments for a preferable reading pattern.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...