user2843341
user2843341

Reputation: 303

Inline method to read a resource file .txt

Following my code I used when I did not put the file "text.txt" in the resource files:

System.IO.StreamReader file = new System.IO.StreamReader("text.txt");

Now the file "text.txt" is in the resource files, this code it gives me error. How to solve?

Upvotes: 1

Views: 396

Answers (1)

makim
makim

Reputation: 3284

If you add a Textfile to your Resources, than you can get the Content of this Textfile as String via Properties.Resources:

string textFileContent = Properties.Resources.NameOfYourResource

You could also make a Property to access your the Content of your ResourceFile:

public string YourResource
{
    get
    {
        return Properties.Resources.NameOfYourResource
    }
}

If you want to read your ResourceFile Line by Line or mabe only the first line:

string text = Properties.Resources.text;

        using(TextReader sr = new StringReader(text))
        {
            var firstline = sr.ReadLine();
            Console.WriteLine("FIRSTLINE: " + firstline);

            string line;
            while ((line = sr.ReadLine()) != null)
            {
                Console.WriteLine(line);
            }
        }

Upvotes: 3

Related Questions