【问题标题】:Having trouble while adding double quotes to a string that is inside a variable in C#?向 C# 中变量内的字符串添加双引号时遇到问题?
【发布时间】:2018-05-30 05:00:18
【问题描述】:

我正在尝试将filepath 传递给xcopy command 以将文件夹从一个位置复制到另一个位置(CodedUI using C#)。 虽然做同样的问题是,我试图在路径周围添加双引号,但它没有采用正确的路径格式。

Code: 
string Path = "Some path to folder location";

// Tried all these solutions

Path = '\"' + Path + '\"';
Path = '\"' + Path + '\"';
Path = string.Format("\"{0}\"", Path );

预期:""Some path to folder location"" 实际:"\"Some path to folder location"\"

请帮忙。

【问题讨论】:

  • 这个也是:Path = "\"" + Path + "\"";
  • 您的预期输出是“文件夹位置的某个路径”。我说的对吗?
  • @Doruk 就是这样。

标签: c# coded-ui-tests xcopy


【解决方案1】:

在调试器中你会看到反斜杠。

将你的输出发送到控制台,你会看到结果很好。

 string Path = "Some path to folder location";

 Path = "\"" + Path + "\"";
 Console.WriteLine(Path);

【讨论】:

    【解决方案2】:

    据我了解,你想看

    “文件夹位置的一些路径”

    当您打印它时。如果是这样,请这样做:

    string path = "\"Some path to folder location\"";
    

    string path = "Some path to folder location";
    var finalString = string.Format("\"{0}\"", path);
    

    【讨论】:

      【解决方案3】:

      也许你应该尝试像@"the\path\to\another\location"这样的逐字字符串。
      这是编写路径的最佳方式,无需与转义码作斗争。

      编辑:
      您可以在逐字字符串中使用双引号:
      @"""the\path\to\another\location"""

      【讨论】:

        【解决方案4】:

        如果您要保留两组双引号,请尝试像这样构建字符串:

        var path = "hello";
        var doubleQuotes = "\"\"";
        var sb = new StringBuilder(doubleQuotes)
            .Append(path)
            .Append(doubleQuotes);
        Console.WriteLine(sb.ToString()); // ""hello""
        

        当然,如果你想要单引号,你只需将doubleQuotes 换成singleQuotes = "\""; 并得到"hello"

        【讨论】:

          【解决方案5】:

          要添加双引号,你需要在'"'之前添加'\'。

          请注意:如果您在 path 中有“\”,则必须像下面这样处理它。

          如果路径是“D:\AmitFolder”

          string path = @"D:\AmitFolder"; 
          //Or
          path = "D:\\AmitFolder"
          string str = "\"" + path + "\"";
          Console.WriteLine(str);
          

          这里的 str 将是“文件夹位置的某个路径”

          输出:

          如上一行,我们添加"\"" 字符串作为前缀,"\"" 作为主字符串的后缀。

          【讨论】:

          • 不工作意味着什么?你从中得到了什么输出。
          • @bankarpit 我对我的回答做了一些修改。看看,如果它可以帮助你
          【解决方案6】:

          在存储字符串值时,如果要添加任何双引号,则需要使用反斜杠(\)对其进行转义。单引号用于字符数据。下面的代码应该得到所需的输出。

          Path = string.Format("\"{0}\"", Path);
          

          我还创建了一个小小提琴here

          【讨论】:

            猜你喜欢
            • 2011-04-23
            • 2013-01-15
            • 2020-10-09
            • 1970-01-01
            • 1970-01-01
            • 2020-05-12
            • 2014-04-24
            • 1970-01-01
            相关资源
            最近更新 更多