如何逃生路径包含空格 [英] How to escape spaces containing path

查看:113
本文介绍了如何逃生路径包含空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要通过空格以.NET控制台应用程序,你应该逃避它的路径。大概不会逃跑,但用双引号包围:

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 变成新的字符串[] {--path,C:\Program,Files\MyApp}

程序myapp.exe --pathC:\Program Files\MyApp变成新的字符串[] {--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" })))

这成为程序myapp.exe --path C:\Program Files\MyApp --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)

推荐答案

我不认为这是可能的,因为空间为CLI参数的分隔符,这样他们就需要转义。

I don't think it is possible since the space is the delimiter for CLI arguments so they would need to be escaped.

您可以提取此为扩展方法相当不错,所以你可以运行 ARGS .Escape()

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

这篇关于如何逃生路径包含空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆