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.

Recommended Answers

All 6 Replies

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";

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

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.

Side note: Also consider Path.Combine for creating the final path.

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.