【问题标题】:How can I escape the backslash's correctly [duplicate]如何正确转义反斜杠[重复]
【发布时间】:2017-03-03 17:07:10
【问题描述】:

我需要在字符串中转义一些反斜杠 (\)。

我想执行一些命令行命令,但是它的字符串中的转义序列有问题。

这是我的代码:

using (Process P = new Process())
{
    P.StartInfo.FileName = "cmd";
    P.StartInfo.UseShellExecute = false;
    P.StartInfo.RedirectStandardOutput = true;
    P.StartInfo.RedirectStandardInput = true;
    P.StartInfo.CreateNoWindow = true;
    P.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
    P.Start();
    P.StandardInput.WriteLine("@echo off");
    string st = "";
    st = @"@for %%a in (\\192.168.85.245\c\ ) do @for /f '\u0022' tokens=3 '\u0022' %%i in ('dir /-c %%a^|find /i '\u0022' Bytes fre '\u0022'') do (set fs_drive=%%a) & (set fs_space=%%i)";
    P.StandardInput.WriteLine(st);
    P.StandardInput.WriteLine("echo Laufwerk %fs_drive%\\ %fs_space% Bytes Frei");
    P.StandardInput.WriteLine("exit");
    P.WaitForExit();
    System.IO.StreamReader sr = P.StandardOutput;
    test = sr.ReadToEnd();
    sr.Close();
}

问题在于 IP.Address 的位置。 如代码所示,我尝试使用双反斜杠 (\\) 和字符串前面的“@”进行转义。

但在这两种情况下,字符串的值都是:"\\\\192.168.85.245\\c\\"

当我稍后打印字符串时,它会正确打印。但是当我通过 WriteLine 命令在命令行中输入它时,字符串打印不正确。

想要的字符串是"\\192.168.85.245\c\"

希望你能帮助我

【问题讨论】:

  • 当你在 vs 中调试时,你在 st 中得到正确的字符串了吗?
  • \\192.168.85.245\c\ 我编辑了我的问题并添加了它
  • 当你想在你的问题中写反斜杠时,请使用这个`字符(单引号)
  • 你为什么会期待 \\\\192.168.85.245\c\ ?我的意思是,有些斜线要转义,而另一些则不要
  • @ThomasAyoub 这是一个错误对不起

标签: c# string


【解决方案1】:

@ 用于字符串文字:

>string st = @"@for %%a in (\\192.168.85.245\c\ ) do @for /f '\u0022' tokens=3 '\u0022' %%i in ('dir /-c %%a^|find /i '\u0022' Bytes fre '\u0022'') do (set fs_drive=%%a) & (set fs_space=%%i)";
>Console.WriteLine(st);
@for %%a in (\\192.168.85.245\c\ ) do @for /f '\u0022' tokens=3 '\u0022' %%i in ('dir /-c %%a^|find /i '\u0022' Bytes fre '\u0022'') do (set fs_drive=%%a) & (set fs_space=%%i)
             ^^^^^^^^^^^^^^^^^^^

您的 IP 已经形成。使用调试器查看它时,您会看到它已转义:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-27
    • 2011-01-11
    • 1970-01-01
    相关资源
    最近更新 更多