开发者

How to retrieve a binary file from .NET assembly?

开发者 https://www.devze.com 2022-12-25 06:41 出处:网络
I have an excel file that I want to embed in my C# assembly. I have changed the build action of the XLSX file to \"Embedded Resource\".

I have an excel file that I want to embed in my C# assembly. I have changed the build action of the XLSX file to "Embedded Resource".

During runtime, I have to retrieve this XLSX file from the assembly.

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

As expected, this fails for the XLSX file since it is a binary data. This cou开发者_如何转开发ld works well with a text file.

I tried binary read/write, but I am not able to get the code running. Thoughts?


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

精彩评论

暂无评论...
验证码 换一张
取 消