can anyone tell me if it is possible in C# to open a file which is located in the same folder as the application without specifying the path to that file?

if both file and program is located for example on C:/containfileandprog can i open the file from within a program without writing C:/containfileandprog but just the filename.dat?

i have no control on where the file or the program is going to be installed so i cant specify them in advance. but i can make sure that they both end up in the same folder where ever the enduser might want to put them.

9 Years
Discussion Span
Last Post by JOSheaIV

to open a file that's beside your application

Application.StartupPath returns the path where your application starts from

Example to open text file called 1.txt which is beside your .exe

System.Diagnostics.Process.Start(Application.StartupPath + "\\1.txt");

if you are doing console, it should work like this:

string _sAppPathName = Process.GetCurrentProcess().MainModule.FileName; 

string _sDataFilePath = _sAppPath.Substring(0, _sAppPath.Length - (_sAppPath.Length - _sAppPath.LastIndexOf(@"\"))) + @"\yourfilename.yourextension";

Unless you're changing the working directory, you could use something like this:

string path = System.IO.Directory.GetCurrentDirectory() + @"\1.txt";
string[] FileContents = System.IO.File.ReadAllLines(path);

Which works in both forms and consoles.


Correct me if I am wrong, but can't you simply specify the file name and extension?

I know when I did some earlier coding in C#, since the .exe and saved file were in the same folder, I didn't need to specify a path, but simply the file name.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.