File.Exists

  • Thread starter Thread starter PiotrKolodziej
  • Start date Start date
P

PiotrKolodziej

Hi
I want to check if the file can be executed. Its directory path is either in
environment 'path' variable or isn't there.
Exists method seems like it's not checking variables at all.
For any help thanks.
 
You just need to create a function to expand the variables and do your
testing. A better option than below is to create a singleton to do this so
you take advantage of caching the paths and/or executable name arguments if
this function is used often.


class Program
{
static void Main(string[] args)
{
Console.WriteLine(ExecutableExists("A Non Existant
File.exe").ToString());
Console.WriteLine(ExecutableExists("Notepad.exe").ToString());
Console.ReadLine();
}

static bool ExecutableExists(string executableName)
{
if (string.IsNullOrEmpty(executableName))
{
return false;
}
string[] paths =
Environment.ExpandEnvironmentVariables("%Path%").Split(';');
string path = null;
foreach (string environmentPath in paths)
{
path = System.IO.Path.Combine(environmentPath,
executableName);
if (System.IO.File.Exists(path))
{
return true;
}
}
return false;
}
}
 
PiotrKolodziej,

The static Exists method is not guaranteed to return whether or not the
file can be executed. It only tells you if the file exists, and you have
the required permissions to access it.

What exactly are you trying to do?
 
Back
Top