Reputation: 13
If possible, how would you force C# code to run any given file as an exe even when the extension isn't .exe
?
For example, my code extracts an exe from the program's resources into the user's roaming folder and starts it; GetRandomFileName()
returns XXXXXX.XXX with Xs being random characters, but if I try to do:
string exePath = @"C:\Users\" + Environment.UserName + @"\AppData\Roaming\" + Path.GetRandomFileName();
using (FileStream exeFile = new FileStream(exePath, FileMode.CreateNew))
exeFile.Write(exeBytes, 0, exeBytes.Length);
process.StartInfo = processStartInfo;
processStartInfo.FileName = exePath;
Process.Start();
I get an error as Windows tries launching the program as a .XXX (whatever the random file extension may be).
Upvotes: 1
Views: 490
Reputation: 70661
Just set UseShellExecute
to false
:
process.StartInfo = processStartInfo;
processStartInfo.FileName = exePath;
processStartInfo.UseShellExecute = false;
Process.Start();
By default, Process
will use the Windows Shell to try to start your file. The Shell looks at the extension to figure out which program should actually run. Known-executable files are run directly, but any other file is checked for file extension associations. If none is present, you get the prompt to find a program to run it.
You can bypass all of that by setting UseShellExecute
to false
. That forces the Process
class to just use the native CreateProcess()
function directly. That function doesn't have any trouble starting any valid executable file, regardless of file name.
Upvotes: 6