如何转义包含空格的路径

发布于 2024-09-19 08:32:04 字数 737 浏览 4 评论 0原文

要将带有空格的路径传递给 .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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

花辞树 2024-09-26 08:32:04

我认为这是不可能的,因为空格是 CLI 参数的分隔符,因此需要对它们进行转义。

您可以很好地将其提取到扩展方法中,这样您就可以在上面的代码中运行 args.Escape() 。

public static string[] Escape(this string[] args)
{
    return args.Select(s => s.Contains(" ") ? string.Format("\"{0}\"", s) : s).ToArray();
}

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.

public static string[] Escape(this string[] args)
{
    return args.Select(s => s.Contains(" ") ? string.Format("\"{0}\"", s) : s).ToArray();
}
粉红×色少女 2024-09-26 08:32:04

只需引用每个参数即可。这...

myapp.exe "--path" "C:\Program Files\MyApp" "--flag"

...是一个完全有效的命令行,并且完全符合您的要求。

Just quote every parameter. This...

myapp.exe "--path" "C:\Program Files\MyApp" "--flag"

...is a perfectly valid command line and does exactly what you want.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文