How to get binary file from .NET assembly?

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

At runtime, I have to extract 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 because it is binary data. This may work well with a text file.

I tried binary read / write, but I cannot run the code. Thoughts?

+3
source share
1 answer
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);
}
+10
source

Source: https://habr.com/ru/post/1739665/


All Articles