s1nisteR
s1nisteR

Reputation: 1

How to check if a file exists or not in the directory the executable is?

How can I check if a file exists or not in the directory the executable is? I know how I could code it like this.

string path = Application.StartupPath + "config.cfg"
if(!FileExists(path))
{
//create the file
}

But the problem I am facing is that, the file is created every single time, even when the file exists, overwriting the data of the cfg file with the default ones.

Upvotes: 0

Views: 980

Answers (1)

Habib
Habib

Reputation: 223187

You are not creating the possible file path properly. Use Path.Combine like:

string path = Path.Combine(Application.StartupPath, "config.cfg");

You are getting a path without terminating \ from Application.StartupPath, later you are concatenating the file name to it, This will create an invalid path, and since that doesn't exist, you check fails.

Just to show, the actual reason for getting the error, you can fix your code like:

string path = Application.StartupPath +"\\"+ "config.cfg";

But, do not use the above code, instead use Path.Combine to join multiple path elements.

Upvotes: 2

Related Questions