Insert any binary file in C# assembly and extract it at runtime

by rahul 4/3/2010 1:03:40 PM

Problem> There is a binary file (I’ll use an Excel file) that you want to embed in any C# assembly. Later on, at runtime, you want to extract the file from the EXE and continue working on it. In this post, I will share the code and describe how you can do that. You can use the same technique for any other kind of binary file as well.

Solution> First up, the reason why you may choose to embed a resource directly into your EXE is to ensure that no one tampers your file on which your code is based. This post doesn’t talk about handling an Excel file. It mainly focuses on two parts… embedding any file directly in your EXE, and then extract it at runtime and execute it.

    Create a new Windows Forms Project
    Add an Existing file (I’ve added a file called File.xlsx) in the project
    Right click on File.xlsx and select Properties
    Change the Build Action –> Embedded Resource

image

    Switch to the form where you want to extract and use this resource
    Add the following to the top of the code behind…

using System.Reflection;
using System.IO;

     Add the following methods and call ExtractFromAssembly method.

private void ExtractFromAssembly()
{
    string strPath = Application.LocalUserAppDataPath + "\\OutputFile.xlsx";
    if (File.Exists(strPath)) File.Delete(strPath);
    Assembly assembly = Assembly.GetExecutingAssembly();
    //In the next line you should provide NameSpace.FileName.Extension that you have embedded
    var input = assembly.GetManifestResourceStream("Sample.File.xlsx");
    var output = File.Open(strPath, FileMode.CreateNew);
    CopyStream(input, output);
    input.Dispose();
    output.Dispose();
    System.Diagnostics.Process.Start(strPath);
}

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

     Yes, that’s pretty much it!

Hope this helps, Wave
Rahul


Quote of the day:
I'm an idealist. I don't know where I'm going, but I'm on my way. - Carl Sandburg


blog comments powered by Disqus

Rahul Soni

Rahul Soni  Twitter

 LinkedIn

 Facebook

 Email me



Vivek Kumbhar

Vivek Kumbhar  Twitter

 LinkedIn

 Facebook

 Email me


Stack Exchange

profile for Vivek at Server Fault, Q&A for system administrators and IT professionals

profile for Rahul Soni at Stack Overflow, Q&A for professional and enthusiast programmers

Calendar

<<  February 2012  >>
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
2728291234
567891011

View posts in large calendar

All Items
Sign in

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.
© Copyright 2012, Rahul Soni

Powered by BlogEngine.NET 1.4.5.0