Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
926 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...