Bassie Bassie - 2 months ago 40
C# Question

Process.Start Throwing Win32Exception when File not Found

Update



The documentation states:

FileNotFoundException:


The file specified in the startInfo parameter's FileName property could not be found.


In the case below, the file cannot be found, yet the code throws a different exception. That is at least very misleading if not completely untrue.

The only explanation I can think of is that the program tries to run the file without checking whether it exists. This is fair enough, but then in what scenario would
FileNotFoundException
ever even happen?

Is this an error in the documentation?




I am trying to call
Process.Start()
on an executable. If the file cannot be found, it should be copied into the required location and then try again.

According to the documentation,
Process.Start()
can throw a
FileNotFoundException
when
The file specified in the startInfo parameter's FileName property could not be found.


Based on that, the following would seem like a reasonable approach:

try
{
Process.Start(@"C:\users\Angus.McAngerson\desktop\IT Self Help.exe");
}
catch (FileNotFoundException ex)
{
File.Copy(@"Z:\Unused\Apps\IT Support App\IT Self Help.exe", @"C:\users\Angus.McAngerson\desktop");
Process.Start(@"C:\users\Angus.McAngerson\desktop\IT Self Help.exe", "vdi");
}


However, the
Start()
in the
try
block only ever throws a
Win32Exception
:


An unhandled exception of type 'System.ComponentModel.Win32Exception' occurred in System.dll

Message: The system cannot find the file specified

ErrorCode: -2147467259

NativeErrorCode: 2


I tried changing the
try
code to:

var procsi = new ProcessStartInfo(@"C:\users\Angus.McAngerson\desktop\IT Self Help.exe");
Process.Start(procsi);


But with the same results. I also tried changing the BuildPlatform to
x86
,
x6
and
Any CPU
but without any difference.

Why is this happening? How can I throw a
FileNotFoundException
?

Answer

If you look here: https://msdn.microsoft.com/en-us/library/system.componentmodel.win32exception(v=vs.110).aspx

It will show you that you'll get the Win32Exception when trying to open an executable that doesn't exist.

So actually, your code seems to be functioning fine.

But if you really want a FileNotFoundException, then you're gonna have to do some checks yourself before running the process and throw the exception yourself.

if(!File.Exists(@"C:\users\Angus.McAngerson\desktop\IT Self Help.exe"))
{
     throw new FileNotFoundException("This file was not found.");
}

Edit

It does seem as though there may be an error in the documentation as I can't get it to throw the FileNotFoundException either, even though it claims to be able to.

So, you can either handle the Win32Exception or do what I suggested above.

Maybe someone else can shed light on this?