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

后端 未结 4 1007
天命终不由人
天命终不由人 2020-12-02 01:38

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 :



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

    Keep in mind that Embedded resource filename = Assemblyname.fileName

    string fileName = "test.pdf";
    System.Reflection.Assembly a = 
    System.Reflection.Assembly.GetExecutingAssembly();
            string fileName = a.GetName().Name + "." + 
    "test.pdf";
            using (Stream resFilestream = 
     a.GetManifestResourceStream(fileName))
            {
                if (resFilestream == null) return null;
                byte[] ba = new 
    byte[resFilestream.Length];
                resFilestream.Read(ba, 0, ba.Length);
                var byteArray= ba;
            }
    
    0 讨论(0)
  • 2020-12-02 02:10

    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.

    0 讨论(0)
  • 2020-12-02 02:11

    Simple alternative using a MemoryStream:

    var ms = new MemoryStream();
    await resFilestream.CopyToAsync(ms);
    var bytes = ms.ToArray();
    
    0 讨论(0)
  • 2020-12-02 02:20
    File.WriteAllBytes(@"C:\Users\admin\Desktop\MyFile.exe", Resources.BinFile); // binary file
    File.WriteAllText(@"C:\Users\admin\Desktop\text.txt", Resources.TextFile); // text file
    
    0 讨论(0)
提交回复
热议问题