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

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

问题描述

要将带有空格的路径传递给.NET控制台应用程序,您应该将其转义。可能不会逃脱,但用双引号环绕:

  myapp.exe --path C:\Program Files\MyApp` 

成为

  new string [] {--path,C:\Program,Files\MyApp} 

但是

  myapp.exe --pathC:\Program Files\MyApp 

成为

  new string [] {--path,C:\Program Files\MyApp} 

,它的工作正常,你可以很容易地解析。



我想扩展一组添加的参数,并开始一个新的过程结果一组参数:

  new ProcessStartInfo(
Assembly.GetEntryAssembly()。位置,
String.Join(,Enumerable.Concat(args,new [] {--flag})))

这将成为 myapp.exe --path C:\Program File s\MyApp --flag 哪里路径丢弃它的转义。



如何解决它与常见的解决方案? (没有搜索每个参数的值需要转义和手动引用)

解决方案

我不认为这是可能的,因为空间是用于CLI参数的分隔符,以便它们需要转义。



您可以非常好地将其解压缩到扩展方法中,以便您可以运行 args 。

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


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)

解决方案

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

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

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