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

我的梦境 提交于 2019-11-27 09:40:14

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.

 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;
        }`
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!