0

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

Keavon
  • 6,837
  • 9
  • 51
  • 79
  • Just use the file name. The working directory is always the executable directory. – Simon Whitehead Mar 03 '14 at 04:53
  • @SimonWhitehead: That is not true at all. If you run "c:\foo\program.exe" from some other directory, the current working directory will be the directory you're in, *not* "c:\foo\". – Jim Mischel Mar 03 '14 at 05:02

3 Answers3

5

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.

Community
  • 1
  • 1
Jim Mischel
  • 131,090
  • 20
  • 188
  • 351
1
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.

Sriram Sakthivel
  • 72,067
  • 7
  • 111
  • 189
  • `File.ReadLines("names.txt")` will not necessarily read from the directory that contains the .exe. It will read from the current working directory. – Jim Mischel Mar 03 '14 at 04:57
1

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

Keshavdas M
  • 674
  • 2
  • 7
  • 25