Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying embedded resource as file to disk in C#

I have an INF file saved as an embedded resource in my C# project. I am trying to save this file to a local location on demand. I am using this method.

public static void SaveResourceToDisk(string ResourceName, string FileToExtractTo)
{
    Stream s = Assembly.GetExecutingAssembly().GetManifestResourceStream(ResourceName);
    FileStream resourceFile = new FileStream(FileToExtractTo, FileMode.Create);

    byte[] b = new byte[s.Length + 1];
    s.Read(b, 0, Convert.ToInt32(s.Length));
    resourceFile.Write(b, 0, Convert.ToInt32(b.Length - 1));
    resourceFile.Flush();
    resourceFile.Close();

    resourceFile = null;
}

When I try to call this method (passing the resource name along with the namespace name), I get the error:

Object reference not set to an instance of an object

What am I doing wrong here?

like image 802
GPX Avatar asked Dec 10 '10 04:12

GPX


2 Answers

You could call

System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceNames();

And inspect which embedded resources are accessible. Then you can compare that against what you are passing in to see if you are indeed accomplishing what you expected to.

Also, you should consider the using keyword to dispose of your streams:

using(FileStream ResourceFile = new FileStream(FileToExtractTo, FileMode.Create))
{
    //do stuff
}

Good luck.

like image 175
dreadwail Avatar answered Oct 25 '22 04:10

dreadwail


This is the easiest way to save an embedded resource:

  var stream = assembly.GetManifestResourceStream("name of the manifest resourse");
  var fileStream = File.Create(@"C:\Test.xml");
  stream.Seek(0, SeekOrigin.Begin);
  stream.CopyTo(fileStream);
  fileStream.Close();
like image 39
A-Sharabiani Avatar answered Oct 25 '22 03:10

A-Sharabiani