7

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.

StayOnTarget
  • 11,743
  • 10
  • 52
  • 81
Sako73
  • 9,957
  • 13
  • 57
  • 75

3 Answers3

8

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")
twoflower
  • 6,788
  • 2
  • 33
  • 44
6

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 ...
  }
Martin Liversage
  • 104,481
  • 22
  • 209
  • 256
0

One method that worked for my use case was from the following answer: https://stackoverflow.com/a/34664553/11860907

For Binary files: File.WriteAllBytes(outputpath, Properties.Resources.file);

For Text files: File.WriteAllText(outputpath, Properties.Resources.file);

I just ran this line of code for every embedded resource file I needed when my program first opened and it placed the resource files somewhere that I could then reference as a string path.

Jay Brown
  • 139
  • 2
  • 13