Question

I'm reading and writing to some text files and I'm currently using a set path. How can I change that set path to use the same folder where the executable resides?

For example:

File.ReadLines(@"D:\Users\MyUserName\Desktop\MyApplication\names.txt").Skip(1).ToList();

and...

File.WriteAllLines(@"D:\Users\MyUserName\Desktop\MyApplication\names.txt", lines);

and...

using (StreamWriter writer = new StreamWriter(@"D:\Users\MyUserName\Desktop\MyApplication\names.txt", true))
{
    writer.WriteLine(myText);
}

It also needs to work when testing in the IDE (Visual Studio).

Was it helpful?

Solution

The path is relative to the current working directory. When running in the IDE, that will be the directory in which the executable resides. Otherwise it's typically the directory in which you started the program.

So if your current directory (on the command line) is C:\foo and you enter the command "C:\bar\myprogram.exe", your program will start in C:\foo and if you try to open the file "fooby.txt", it will look for "C:\foo\fooby.txt".

See How do I get the name of the current executable in C#? for information about how to get the executable file path.

OTHER TIPS

Assembly.GetEntryAssembly().Location

If you're in winforms app you may use

System.Windows.Forms.Application.StartupPath

By default it will be pointed to the current directory as @JimMischel said.

So better avoid just using filenames like this File.ReadLines("names.txt"); instead provide full file path.

You can also use Environment.CurrentDirectory to get the current application folder Check the LINK for more details

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top