views:

230

answers:

3

I have a rather large resource (2MB) that I'm embedding into my C# application ... I want to know read it into memory and then write it to disk to use it for later processing?

I've embedded the resource into my project as build setting

Any sample piece of code will help me startup.

A: 
var assembly = Assembly.GetExecutingAssembly();
using (var stream = assembly.GetManifestResourceStream("namespace.resource.txt"))
{
    byte[] buffer = new byte[stream.Length];    
    stream.Read(buffer, 0, buffer.Length);
    File.WriteAllBytes("resource.txt", buffer);
}
Darin Dimitrov
+1  A: 

You need to Stream in the resource from Disk, since the .NET Framework likely won't load your resources until you access them (I'm not 100% sure, but I'm fairly confident)

While you stream the contents in, you need to write them back as well to disk.

Remember, this will create the filename as "YourConsoleBuildName.ResourceName.Extenstion"

For example, if your project target is called "ConsoleApplication1", and your resource name is "My2MBLarge.Dll", then your file will be created as "ConsoleApplication1.My2MBLarge.Dll" -- Of course, you can modify it as you see fill fit.

    private static void WriteResources()
    {
        Assembly assembly = Assembly.GetExecutingAssembly();
        String[] resources = assembly.GetManifestResourceNames();
        foreach (String name in resources)
        {
            if (!File.Exists(name))
            {
                using (Stream input = assembly.GetManifestResourceStream(name))
                {
                    using (FileStream output = new FileStream(Path.Combine(Path.GetTempPath(), name), FileMode.Create))
                    {
                        const int size = 4096;
                        byte[] bytes = new byte[size];

                        int numBytes;
                        while ((numBytes = input.Read(bytes, 0, size)) > 0)
                            output.Write(bytes, 0, numBytes);
                    }
                }
            }
        }
    }
mjsabby
works ... thanks add exception handling
halivingston
A: 

Try the following:

Assembly Asm = Assembly.GetExecutingAssembly();
var stream = Asm.GetManifestResourceStream(Asm.GetName().Name + ".Resources.YourResourceFile.txt");
var sr = new StreamReader(stream);
File.WriteAllText(@"c:\temp\thefile.txt", sr.ReadToEnd);

The code assumes that your embedded file is called YourResourceFile.txt and that it is in a folder in your project called Resources. And of course the folder c:\temp\ must exist and be writeable.

Hope it helps.

/Klaus

klausbyskov