2012-05-02 35 views
16

在我的应用程序编译使用CodeDom.Compiler从source.cs文件的另一个计划,我使用嵌入在编译时的一些资源(EXE和DLL文件):如何以字节数组的形式读取嵌入式资源而不将其写入磁盘?

// .... 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 

在编译的文件,我需要阅读作为字节数组的嵌入式资源。我现在做的是使用下面的功能和使用提取的资源到磁盘

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

我做到这一点使用此功能的两个文件解压到硬盘后:

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

我怎样才能做同样的事情(获取嵌入资源作为字节数组),但不写任何东西到硬盘?

回答

23

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

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

编辑:请参阅注释以获得更好的阅读模式。

+1

更新了我的答案,当你已经读取流到一个字节数组时,不需要内存流。 – Rotem

+2

这可能无法正常工作,因为Stream.Read()可能不会在一个Read()中返回所有数据。我不确定这个特定的'Stream'如何表现,但为了安全起见,我将使用'MemoryStream','CopyTo()',然后使用'ToArray()'。 – svick

+0

@svick:你说得对。或者,可以使用本页示例中描述的阅读模式:http://msdn.microsoft.com/en-us/library/system.io.stream.read.aspx – Rotem

相关问题