user2726194
user2726194

Reputation: 21

Read .txt embedded as resource

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)

Upvotes: 2

Views: 1353

Answers (2)

Chris
Chris

Reputation: 27629

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).

Upvotes: 3

Shaharyar
Shaharyar

Reputation: 12449

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

Upvotes: 0

Related Questions