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

本文关键字:运行 命令行 参数 | 更新日期: 2023-09-27 17:56:11

可以使用

如下所示的内容在 c# 中运行命令行:

process = new Process();
process.StartInfo.FileName = command;
process.Start();

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

C:'My Dir'MyFile.exe MyParam1 MyParam2

这行不通,我不知道如何从这个字符串中提取参数并将其设置在 process.Arguments 属性上?路径和文件名可以是其他内容,文件不必以 exe 结尾。

我该如何解决这个问题?

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

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

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(); 

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

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

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 );

断言:如果文件名包含空格,则必须用双引号括起来。

在Windows中肯定是这种情况。否则,规则将变得更加上下文相关。

看看正则表达式

匹配空格但不在字符串中,我怀疑你可以使用正则表达式,

" +(?=(?:[^'"]*'"[^'"]*'")*[^'"]*$)"

使用 Regex.Split() 将命令行转换为数组。第一部分应该是您的文件名。