It's possible to run commandline in c# by using something like this :
process = new Process();
process.StartInfo.FileName = command开发者_如何学Go;
process.Start();
The problem is if the command string contains parameters, for example:
C:\My Dir\MyFile.exe MyParam1 MyParam2
This will not work and I don't see how to extract the parameters from this string and set it on the process.Arguments
property? The path and filename could be something else, the file does not have to end with exe
.
How can I solve this?
If I understand correctly I would use:
string command = @"C:\My Dir\MyFile.exe";
string args = "MyParam1 MyParam2";
Process process = new Process();
process.StartInfo.FileName = command;
process.StartInfo.Arguments = args;
process.Start();
If you have a complete string that you need to parse I would use the other methods put forward by the others here. If you want to add parameters to the process, use the above.
This could be the worst solution, but it could a safer one:
string cmd = "C:\\My Dir\\MyFile.exe MyParam1 MyParam2";
System.IO.FileInfo fi = null;
StringBuilder file = new StringBuilder();
// look up until you find an existing file
foreach ( char c in cmd )
{
file.Append( c );
fi = new System.IO.FileInfo( file.ToString() );
if ( fi.Exists ) break;
}
cmd = cmd.Remove( 0, file.Length );
System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo( fi.Name, cmd );
System.Diagnostics.Process.Start( psi );
Assertion: If a filename contains a space, it must be wrapped in double quotes.
This is certainly the case in Windows. Otherwise the rules become much more contextual.
Have a look at regex-matching-spaces-but-not-in-strings, I suspect you can use the regex,
" +(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)"
using Regex.Split()
to convert you command line into an array. The first part should be your filename.
精彩评论