Reputation: 2802
If my executable is running from a path with no spaces, this
if(!File.Exists(@"\program.exe"))
MessageBox.Show("File not found");
doesn't fire. But, if the program executes from a path with spaces, like C:\Program Files\etc\
I get a file not found. My executable application and program.exe
lies in the same folder.
How can I avoid this?
Upvotes: 3
Views: 3581
Reputation: 913
To check the existence of your file in the "current directory", you have not to put the "\" character. So:
if(!File.Exists("program.exe"))
MessageBox.Show("File not found");
Here a little explanation.
Upvotes: 0
Reputation: 67928
Though it may seem like the path has something to do with it, it's the Working Directory. Try this code:
var path = Path.Combine(
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
"program.exe");
if (!File.Exists(path))
The path in which is it launched wouldn't cause that code to fail. However, when the working directory isn't what's expected; that will.
Furthermore, never assume that you're in a specific directory. Always provide a fully qualified path. Objects like the SaveFileDialog
and OpenFileDialog
can change the working directory on you at runtime.
Upvotes: 4
Reputation: 4960
File.Exist(@"\program.exe")
will check for program.exe at the root of the drive, eg c:\program.exe if your program is running from c:
Upvotes: 0
Reputation: 62265
I would simply remove "\"
from the argument of the method File.Exists(@"program.exe")
, and check the current working directory by GetCurremtDirectory to be sure that relative path you are passing (that is relative path) constructs correct full path to executable.
Upvotes: 0
Reputation: 6276
Just get the execution directory path and append it to your exe
file name
string DirPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
if(!File.Exists(DirPath + @"\program.exe"))
MessageBox.Show("File not found");
Upvotes: 1