Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to get a string path reference to an embedded resource file?

Tags:

c#

.net

I have a method that takes a string parameter that is a file path to a text file. I want to be able to pass in a text file that I have embedded as a resource in my assembly.

Is there any way to get a string reference to an embedded text file so that it would function as a file path for opening a StreamReader?

Thanks.

like image 913
Sako73 Avatar asked Aug 09 '12 22:08

Sako73


2 Answers

You can use Assembly.GetManifestResourceStream(resource_name_of_the_file) to access the file's stream, write it to TEMP directory and use this path.

For example, if you have a file in your project at the path "Resources\Files\File.txt" and the project's assembly default namespace is "RootNamespace", you can access the file's stream from within this assembly's code with

Assembly.GetExecutingAssembly().GetManifestResourceStream("RootNamespace.Resources.Files.File.txt")
like image 185
twoflower Avatar answered Nov 08 '22 01:11

twoflower


Is there any way to get a string reference to an embedded text file so that it would function as a file path for opening a StreamReader?

No, an embeded resource is not a separate file but embedded into the executable file. However, you can get a stream that you can read from using a StreamReader.

var name = "...";
using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(name)) 
  using (var streamReader = new StreamReader(stream)) {
    // Read the embedded file ...
  }
like image 41
Martin Liversage Avatar answered Nov 08 '22 01:11

Martin Liversage