如何转义包含空格的路径
要将带有空格的路径传递给 .NET 控制台应用程序,您应该转义它。可能不是转义,而是用双引号括起来:
myapp.exe --path C:\Program Files\MyApp`
成为
new string[] { "--path", "C:\Program", "Files\MyApp" }
但
myapp.exe --path "C:\Program Files\MyApp"
成为
new string[] { "--path", "C:\Program Files\MyApp" }
并且它工作正常,您可以轻松解析它。
我想扩展给定的一组参数,并使用生成的参数集启动一个新进程:
new ProcessStartInfo(
Assembly.GetEntryAssembly().Location,
String.Join(" ", Enumerable.Concat(args, new[] { "--flag" })))
这将变为 myapp.exe --path C:\Program Files\MyApp --flag
路径放弃转义的地方。
如何用常见的解决方案来解决这个问题? (无需搜索需要转义并手动引用的每个参数的值)
To pass a path with spaces to .NET console application you should escape it. Probably not escape but surround with double quotes:
myapp.exe --path C:\Program Files\MyApp`
becomes
new string[] { "--path", "C:\Program", "Files\MyApp" }
but
myapp.exe --path "C:\Program Files\MyApp"
becomes
new string[] { "--path", "C:\Program Files\MyApp" }
and it works fine and you can parse that easily.
I want to extend the set of parameters given with an addition one and start a new process with the resulting set of parameters:
new ProcessStartInfo(
Assembly.GetEntryAssembly().Location,
String.Join(" ", Enumerable.Concat(args, new[] { "--flag" })))
This becomes myapp.exe --path C:\Program Files\MyApp --flag
where path drops its escaping.
How to workaround it with common solution? (without searching each parameter's value requiring escaping and quoting it manually)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为这是不可能的,因为空格是 CLI 参数的分隔符,因此需要对它们进行转义。
您可以很好地将其提取到扩展方法中,这样您就可以在上面的代码中运行 args.Escape() 。
I don't think it is possible since the space is the delimiter for CLI arguments so they would need to be escaped.
You could extract this into an extension method quite nicely so you can just run
args.Escape()
in your code above.只需引用每个参数即可。这...
...是一个完全有效的命令行,并且完全符合您的要求。
Just quote every parameter. This...
...is a perfectly valid command line and does exactly what you want.