【问题标题】:How to get double quotes around folder names with spaces如何在带有空格的文件夹名称周围使用双引号
【发布时间】:2016-04-13 14:18:12
【问题描述】:

这是我的代码

string path1 = @"C:\Program Files (x86)\Common Files";
string path2 = @"Microsoft Shared";
string path = Path.Combine(path1, path2);

Console.WriteLine(path);

输出提供给我

C:\Program Files (x86)\Common Files\Microsoft Shared

我想要任何带有双引号空格的文件夹名称,如下所示

C:\"Program Files (x86)"\"Common Files"\"Microsoft Shared"

我怎样才能得到它?

【问题讨论】:

  • 你确定吗?这有什么用?
  • 我正在创建一个需要这些路径的批处理文件
  • 如果你真的需要它,你可以用“\”替换\
  • 那么您可能想要"C:\Program Files (x86)\Common Files\Microsoft Shared",例如:以" 开头并以" 结尾,我希望您知道该怎么做?

标签: c# .net string path


【解决方案1】:

最简单的方法是使用 LINQ。

您可以将文件夹路径拆分为列出所有文件夹名称的数组,然后使用 Select() 操作每个单独的元素。

在你的情况下,你会想要:

  1. 将字符串拆分为数组(使用“/”分隔元素)
  2. 如果文件夹名称包含空格,则将文件夹名称格式化为"{folderName}"
  3. 以单个字符串的形式重新加入数组,并使用“/”作为分隔符

这是看起来的样子,请注意,为了清楚起见,我使用了 2 个Select() 来帮助识别不同的步骤。它们可以是单个语句。

        string path1 = @"C:\Program Files (x86)\Common Files";
        string path2 = @"Microsoft Shared";
        string path = System.IO.Path.Combine(path1, path2);

        var folderNames = path.Split('\\');

        folderNames = folderNames.Select(fn => (fn.Contains(' ')) ? String.Format("\"{0}\"", fn) : fn)
                                 .ToArray();

        var fullPathWithQuotes = String.Join("\\", folderNames);

上述过程的输出为:

C:\"Program Files (x86)"\"Common Files"\"Microsoft Shared"

【讨论】:

  • 为什么你添加了 .Select(fn => fn.Replace(@"\", "")) ?这似乎是多余的,因为数组文件夹名称不能包含包含 '\\' 字符的元素(由于拆分的工作方式)。
  • @Set 这是我的疏忽,感谢您的关注。我已经相应地更新了答案。
【解决方案2】:

你可以创建一个扩展方法

public static class Ex
{
    public static string PathForBatchFile(this string input)
    {
        return input.Contains(" ") ? $"\"{input}\"" : input;
    }
}

像这样使用它

var path = @"C:\Program Files (x86)\Common Files\Microsoft Shared";
Console.WriteLine(path.PathForBatchFile());

它使用 C# 6.0 中的string interpolation 功能。如果您不使用 C# 6.0,则可以改用它。

public static class Ex
{
    public static string PathForBatchFile(this string input)
    {
        return input.Contains(" ") ? string.Format("\"{0}\"", input) : input;
    }
}

【讨论】:

    猜你喜欢
    • 2012-12-12
    • 1970-01-01
    • 1970-01-01
    • 2021-05-11
    • 2010-09-20
    • 2018-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多