Accessing a local text file in a WPF Application

3.4k Views Asked by At

I'm building an executable application from WPF in visual studio, and I have a local text file added to the project (StringList.txt) that I'm trying to read into a List object. What would the path for that file be for a StreamReader such that the executable can access the file when I deploy it and run in on another computer?

So far I have:

   List<String> list = new List<String>();

   StreamReader sr = new StreamReader("~/Desktop/Deploy/StringList.txt");

    String line = sr.ReadLine();
    while (line != null)
    {
        fields.Add(line);
        line = sr.ReadLine();
    }

    sr.Close();

**Deploy is the publish folder location

1

There are 1 best solutions below

5
On

The ~/Desktop/Deploy/StringList.txt wont work for WPF.. Try this:

// Get the directory where your entry assembly is located (your application)
var assemblyPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);

// Add your sub directory and filename
var filename = assemblyPath + "\\Desktop\\Deploy\\StringList.txt";

// Use it on your StreamReader
StreamReader sr = new StreamReader(filename);

This will open the file within a subdirectory of your program.