如何阅读嵌入的资源作为字节数组,而不将其写入磁盘? [英] How to Read an embedded resource as array of bytes without writing it to disk?

查看:153
本文介绍了如何阅读嵌入的资源作为字节数组,而不将其写入磁盘?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序编译从source.cs文件中使用codeDom.Compiler另一个程序,我嵌入一些资源(EXE和DLL文件)在编译时使用:

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?

推荐答案

您实际上已经读取流的字节数组,为什么不阻止呢?

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;
    }
}

编辑:见为preferable阅读模式的意见

edit: See comments for a preferable reading pattern.

这篇关于如何阅读嵌入的资源作为字节数组,而不将其写入磁盘?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆