2

I have embedded a resource into my code, I want to read the text and apply the text to some string variables. I have worked out how to do that when I use an external file but I only want the .exe

string setting_file = "config.txt";
string complete = File.ReadAllText(setting_file);
string Filename = complete.Split('@').Last(); //"Test.zip"; 
string URL = complete.Split('@').First();

How can I read the resource config.txt (Preferably without new procedures)

John Saunders
  • 160,644
  • 26
  • 247
  • 397
  • http://msdn.microsoft.com/en-us/library/system.resources.resourcemanager.aspx – BartoszKP Aug 28 '13 at 16:22
  • possible duplicate of [How to read embedded resource text file](http://stackoverflow.com/questions/3314140/how-to-read-embedded-resource-text-file) – Alexei Levenkov Aug 28 '13 at 16:22
  • Not quite a duplicate because the question here is about using the resource file without changing the code if possible. Though I would imagine changing the `File.ReadAllText` is probably acceptable but changing to using streams is a bigger change... – Chris Aug 28 '13 at 16:37
  • 1
    See my article, [Embedding a text resource](http://www.informit.com/guides/content.aspx?g=dotnet&seqNum=865) – Jim Mischel Aug 28 '13 at 16:50

2 Answers2

3

The File class is only used for accessing the file system whereas your file is no longer in the system so this line needs to change. As others have hinted with linked answers you need to get the stream for the resource and then read that. The below method can be called to replace your File.ReadAllText method call.

private static string GetTextResourceFile(string resourceName)
{
    var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName);
    using (var sr = new StreamReader(stream))
    {
        return sr.ReadToEnd();
    }
}

The resourceName will be something along the lines of MyNamespace.Myfile.txt. If you are having problems finding your resourcename then the method GetManifestResourceNames on the assembly will help you identify it while debugging.

Also of note is the above method will throw an exception if the resource isn't found. This should be handled in real code but I didn't want to confuse the above sample with standard error handling code.

See also How to read embedded resource text file for a different question with the same answer (that differs in that it asks only about streams but in fact streams seem to be the only way to access embedded resource files anyway).

Community
  • 1
  • 1
Chris
  • 27,210
  • 6
  • 71
  • 92
0

This is how you can use embedded files Properties.Resources.yourfilename

Shaharyar
  • 12,254
  • 4
  • 46
  • 66
  • 1
    This only seems to work with strings added through the resource manager. Not with files that are embedded as resources... – Chris Aug 28 '13 at 17:40