使用参数从c#运行命令行?

Ban*_*hee 8 .net c# process

可以使用以下内容在c#中运行命令行:

process = new Process();
process.StartInfo.FileName = command;
process.Start();
Run Code Online (Sandbox Code Playgroud)

问题是如果命令字符串包含参数,例如:

C:\My Dir\MyFile.exe MyParam1 MyParam2
Run Code Online (Sandbox Code Playgroud)

这不起作用,我不知道如何从该字符串中提取参数并在process.Arguments属性上设置它?路径和文件名可能是其他东西,文件不必结束exe.

我怎么解决这个问题?

ano*_*ery 7

如果我理解正确,我会使用:

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(); 
Run Code Online (Sandbox Code Playgroud)

如果你有一个需要解析的完整字符串,我会使用其他人提出的其他方法.如果要向流程添加参数,请使用上面的内容.


ibr*_*ram 5

这可能是最糟糕的解决方案,但也可能是一种更安全的解决方案:

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 );
Run Code Online (Sandbox Code Playgroud)