如何从.NET程序集中检索二进制文件?

Rah*_*oni 3 c# resources embedded-resource

我有一个excel文件,我想嵌入我的C#程序集.我已将XLSX文件的构建操作更改为"嵌入式资源".

在运行时,我必须从程序集中检索此XLSX文件.

Assembly assembly = Assembly.GetExecutingAssembly();
StreamReader sr = new StreamReader(assembly.GetManifestResourceStream("AssemblyName.Output.xlsx"), true);
StreamWriter sw = new StreamWriter(strPath);
sw.Write(sr.ReadToEnd());
sr.Dispose();
sw.Dispose();
System.Diagnostics.Process.Start(strPath);
Run Code Online (Sandbox Code Playgroud)

正如预期的那样,XLSX文件失败,因为它是二进制数据.这适用于文本文件.

我尝试过二进制读/写,但我无法运行代码.思考?

Muh*_*han 10

var assembly = Assembly.GetExecutingAssembly();

// don't forget to do appropriate exception handling arund opening and writing file
using(Stream input = assembly.GetManifestResourceStream("AssemblyName.Output.xlsx"))
using(Stream output = File.Open("output.xlsx"))
{
     input.CopyTo(output);
}
Run Code Online (Sandbox Code Playgroud)