【问题标题】:directory path as string: ensure DirectoryPathSeperator at the end of the string目录路径作为字符串:确保 DirectoryPathSeparator 在字符串的末尾
【发布时间】:2013-02-06 11:12:31
【问题描述】:

.NET 中是否有一种方法可以自动在字符串路径的末尾附加反斜杠?

类似:

var path = @"C:\Windows";
path = Path.GetPathWithSeperatorAtTheEnd(path);
Console.WriteLine(path); 
// outputs C:\Windows\

我目前做的是:

if (!path.EndsWith(@"\")) path += @"\";

编辑:我想要实现的是,如果我将文件名附加到我不需要担心的路径,就会发生类似的事情。或者除了附加路径和文件名还有其他方法吗?

var fullFilename = path + filename;
// path    : C:\Windows
// filename: MyFile.txt
// result  : C:\WindowsMyFile.txt

【问题讨论】:

  • 为什么需要这个?对于目录访问,这不是必需的。

标签: c# .net path


【解决方案1】:

您可以使用:System.IO.Path.Combine

例子:

var path = @"C:\Windows";
path = Path.Combine(path, "win.ini");
// path is @"C:\Windows\win.ini"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-12
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多