Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open a text file with WPF

There is a text file that I have created in my project root folder. Now, I am trying to use Process.Start() method to externally launch that text file.

The problem I have got here is that the file path is incorrect and Process.Start() can't find this text file. My code is as follows:

Process.Start("Textfile.txt");

So how should I correctly reference to that text file? Can I use the relative path instead of the absolute path? Thanks.

Edit: If I change above code to this, would it work?

string path = Assembly.GetExecutingAssembly().Location;
Process.Start(path + "/ReadMe.txt");
like image 244
woodykiddy Avatar asked Jun 10 '11 02:06

woodykiddy


People also ask

How do I read a text file?

To read from a text fileUse the ReadAllText method of the My. Computer. FileSystem object to read the contents of a text file into a string, supplying the path. The following example reads the contents of test.


1 Answers

Windows needs to know where to find the file, so you need somehow specify that:

Either using absolute path:

Process.Start("C:\\1.txt");

Or set current directory:

Environment.CurrentDirectory = "C:\\";
Process.Start("1.txt");

Normally CurrentDirectory is set to the location of the executable.

[Edit]

If the file is in the same directory where executable is you can use the code like this:

var directory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
var file = Path.Combine(directory, "1.txt");
Process.Start(file);
like image 185
Alex Aza Avatar answered Oct 28 '22 11:10

Alex Aza