0

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.

1
  • show us the code for file write Commented Oct 13, 2016 at 16:37

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.