我怎样才能正确地逃避反斜杠

时间:2016-10-21 11:40:18

标签: c# string

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

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

这是我的代码:

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\"

希望你能帮助我

1 个答案:

答案 0 :(得分: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)
             ^^^^^^^^^^^^^^^^^^^

您的知识产权已经形成良好。使用调试器查看它时,您会看到它被转义:

enter image description here