4

I’m using a .NET component that reads specific binary files using a method that expect a string with the full path name like this:

Read("c:\\somefile.ext");

I’ve put the somefile.ext as an embedded resource in my project. Is there any way I can feed some sort of path to the embedded resource to the component’s Read command?

likeitlikeit
  • 5,563
  • 5
  • 42
  • 56
  • 3
    An embedded resource doesn't have a "full path name." You can't refer to it with a file path as though it exists in the file system. Does your component have a `Read` function that will take a `Stream` parameter? – Jim Mischel Sep 22 '13 at 14:46
  • Unfortunately it doesn't. So the simplest option would be to not embed it and 'Copy to output directory"? Thanks! Alex –  Sep 22 '13 at 14:56

2 Answers2

3

The path to the resource is of the form namespace.projectfolder.filename.ext.

In order to read the contents, you can use a helper class like this one

public class ResourceReader
{
    // to read the file as a Stream
    public static Stream GetResourceStream(string resourceName)
    {
        Assembly assembly = Assembly.GetExecutingAssembly();
        Stream resourceStream = assembly.GetManifestResourceStream(resourceName);
        return resourceStream;
    }

    // to save the resource to a file
    public static void CreateFileFromResource(string resourceName, string path)
    {
        Stream resourceStream = GetResourceStream(resourceName);
        if (resourceStream != null)
        {
            using (Stream input = resourceStream)
            {
                using (Stream output = File.Create(path))
                {
                    input.CopyTo(output);
                }
            }
        }
    }
}
shamp00
  • 11,106
  • 4
  • 38
  • 81
  • Thanks Shamp. This helper class works beautifully to extract the embedded file. –  Sep 22 '13 at 17:36
  • 1
    The Stream class has a CopyTo method which can be used instead of your CopyStream. http://msdn.microsoft.com/en-us/library/dd782932.aspx – Jimmy Sep 22 '13 at 18:05
0

You need to use the namespace of the project along with the name of the embedded resource. For example, assume somefile.ext is in the folder resources/files in your project with the name ProjectA. The the correct string you should use to read the embedded resource is:

ProjectA.resources.files.somefile.ext

Filip
  • 656
  • 4
  • 8