【问题标题】:Formating\ parsing string before sending in to process argument在发送到处理参数之前格式化\解析字符串
【发布时间】:2017-10-11 15:44:52
【问题描述】:

有没有一种方法可以删除子字符串之前的 \ 字符,所以在没有它的情况下会有一个引号,就像在“某些文本”中一样,它在将它打印到控制台时会显示出来,但是当它作为一个进程参数,看起来像\" some text\"

示例:

StringBuilder builder = new StringBuilder();
builder.Append("-i some//directory//on//pc//");
builder.Append("somevariables which include white spaces including : // @ chars");
builder.Append("\"this\\is\\another\\directory\\but\\in\\quotation\\marks at the begining\\");
builder.Append("some string variable with an extension such as .mp3 and then end quotation marks\"");
string commandLineArgToAProcess = builder.ToString(); 

process = new Process();
ProcessStartInfo info = new ProcessStartInfo("some\\die\\program.exe",
                        commandLineArgToAProcess);  

process.StartInfo = info;
process.Start();

不确定如何删除引号的开头和结尾之前的 \,该引号在打印到控制台时不会出现,但在将参数传递给进程时会包含它。

也尝试使用 regex.replace 但抛出异常 也尝试过拆分字符串,但每次都意识到字符串长度会有所不同,可能有更好的方法 使用 stringbuilder 时一切正常,但是由于我必须将其转换为 .ToString() 以作为 process 参数,因此它再次添加了反斜杠 无论如何要解决这个问题将不胜感激 谢谢

【问题讨论】:

  • 你试过 System.Text.RegularExpressions.Regex.Unescape 吗?
  • 我还是不明白你为什么要删除它。
  • 我会尝试 regex.unescape 谢谢,我需要删除它,因为它是一组命令,在作为命令行参数发送后由另一个(第三方)程序解码,它不会如果字符串像 "\"directory/save.mp3\" 则工作
  • 在C#代码中字面意思是这样的,但是编译时却不是那样。

标签: c# string replace process split


【解决方案1】:

需要反斜杠来掩盖引号。否则它将被解释为字符串的结尾。这也是为什么在您正在打印的虚构路径中总是有两个反斜杠的原因。第一个掩盖了第二个。如果没有两个反斜杠将与以下符号一起解释。例如 \n 将是一个新行。

您可以在字符串前面加上@ 来禁用屏蔽。但这不适用于引号。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-10
    • 1970-01-01
    • 2019-02-08
    • 2016-08-20
    • 2010-11-23
    • 1970-01-01
    • 1970-01-01
    • 2012-03-03
    相关资源
    最近更新 更多