从 C# 运行带有参数的命令行?
可以使用如下方式在 C# 中运行命令行:
process = new Process();
process.StartInfo.FileName = command;
process.Start();
问题是命令字符串是否包含参数,例如:
C:\My Dir\MyFile.exe MyParam1 MyParam2
这将不起作用,我不知道如何从该字符串中提取参数并将其设置在 < code>process.Arguments 属性?路径和文件名可以是其他名称,文件不必以 exe 结尾。
我该如何解决这个问题?
It's possible to run commandline in c# by using something like this :
process = new Process();
process.StartInfo.FileName = command;
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果我理解正确,我会使用:
如果您有一个需要解析的完整字符串,我会使用其他人在这里提出的其他方法。如果您想向流程添加参数,请使用上面的内容。
If I understand correctly I would use:
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:
断言:如果文件名包含空格,则必须用双引号引起来。
在 Windows 中确实是这样。否则规则就会变得更加贴切。
看看 regex-matching-spaces-but-not-in-strings< /a>,我怀疑您可以使用正则表达式,
使用
Regex.Split()
将命令行转换为数组。第一部分应该是您的文件名。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.