views:

130

answers:

1

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 could works well with a text file.

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

+1  A: 
Assembly assembly = Assembly.GetExecutingAssembly();
var input = assembly.GetManifestResourceStream("AssemblyName.Output.xlsx")
var output = File.Open("output.xlsx");
CopyStream(input, output);


public static void CopyStream(Stream input, Stream output)
{
    byte[] buffer = new byte[32768];
    while (true)
    {
        int read = input.Read (buffer, 0, buffer.Length);
        if (read <= 0)
            return;
        output.Write (buffer, 0, read);
    }
}
Hasan Khan
Thanks a lot Hasan. It worked.
Rahul Soni