I'm writing a toolbox program in C# and on of its functions is to emulate the Windows Start menu "Run" dialog, but also to allow the user to elevate the privileges if needed.
For this, I have a simple WinForm with a textBox (where the user types), and a checkBox (if checked, add the "runas" verb). And of course 3 buttons : OK, Cancel and Browse (which opens a file dialog). So my code looks like this :
var psi = new ProcessStartInfo(textBox1.Text, "");
psi.CreateNoWindow = true;
psi.UseShellExecute = true;
if (checkBox1.Checked == true)
{
psi.Verb = "runas";
}
try
{
Process.Start(psi);
}
catch (System.ComponentModel.Win32Exception ex)
{
// do something
MessageBox.Show("Error : " + ex.Message);
}
If users types "notepad" or "notepad.exe" or "c:\whatever\path\notepad", it works. Problems start to occur when arguments are passed : "notepad test.txt" won't work.
My first thought was to split the textBox1.Text when a space is encountered, then use the first part for the ProcessStartInfo.Filename, and the second part for the Arguments. "notepad test.txt" is ok then. But if the users uses the file dialog to select a file where the path and/or filename contains a space (or types it), of course the string will be splitted and everything will go wrong.
Unfortunately, ParseStartInfo needs both the filename and arguments (can be an empty string), but the filename cannot contain the arguments... Using quotes (for the whole textBox1.Text as filename) doesn't work either.
So, does anyone has a solution to :
- Either split correctly textBox1.Text to valid filename + arguments, just as the Windows Start - Run dialog does it
OR
- Maybe use Shell32.FileRun() but in this case, how to ask for elevation (UAC prompt) at will?
Edit : added the MessageBox.Show to show error messages