目录路径为字符串:确保字符串末尾的DirectoryPathSeperator

Mic*_*ing 1 .net c# path

在.NET中是否有一个方法,它会在一个字符串的路径末尾自动附加一个反斜杠?

就像是:

var path = @"C:\Windows";
path = Path.GetPathWithSeperatorAtTheEnd(path);
Console.WriteLine(path); 
// outputs C:\Windows\
Run Code Online (Sandbox Code Playgroud)

我现在做的是:

if (!path.EndsWith(@"\")) path += @"\";
Run Code Online (Sandbox Code Playgroud)

编辑:我想要实现的是,如果我将文件名附加到一个我不需要担心的路径,那就会发生这样的事情.或者是否有另一种方法而不是追加路径和文件名?

var fullFilename = path + filename;
// path    : C:\Windows
// filename: MyFile.txt
// result  : C:\WindowsMyFile.txt
Run Code Online (Sandbox Code Playgroud)

Cod*_*lla 7

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

例:

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