Home > Uncategorized > Embed managed or unmanaged DLLs in a c# program, by embedding the DLL in a c# program.

Embed managed or unmanaged DLLs in a c# program, by embedding the DLL in a c# program.

Yes, that’s right.

If you want to embed a DLL in a c# program, go ahead, embed it. Then, during run time, take that embedded file and write it somewhere in your search path so that it’s available to your c# program. No magic there.


I’m in the midst of writing an Exchange mailbox searcher CLI program that uses the Exchange Web Services Managed API and Command Line Parser, both of which are most easily dealt with via their DLL.

I began looking for an answer, and I came across this blog post which explains a very simple distribution method for DLLs (or any other files for that matter). Best of all, it’s free (BoxedApp and Redgate have APIs for this sort of thing, and there are some other solutions for managed assemblies like ILMerge).

Here is a solution from the above blog post:

public static void thisisaclass()
{
ExtractResourceToFile("ManagedService.dll", "managedservice.dll");
ExtractResourceToFile("UnmanagedService.dll", "unmanagedservice.dll");
}

public static void ExtractResourceToFile(string resourceName, string filename)
    {
        if (!System.IO.File.Exists(filename))
            using (System.IO.Stream s = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
                using (System.IO.FileStream fs = new System.IO.FileStream(filename, System.IO.FileMode.Create))
                {
                    byte[] b = new byte[s.Length];
                    s.Read(b, 0, b.Length);
                    fs.Write(b, 0, b.Length);
                }
    }
Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: