因此,当我构建一个文件夹/文件检查条件时,同事说使用Path.Combine“更好”:
string finalPath = Path.Combine(folder, "file.txt");
而不是我用
做的方式string finalPath = folder + "\\file.txt";
任何合理的推理都是“更好?”
答案 0 :(得分:7)
这是一个有趣的问题;
当然,您可以写下这样的内容:
string finalPath = String.Format("{0}\\file.txt", folder);
达到你想要的效果。
使用ILSpy,让我们看看为什么Path.Combine更好。
您调用的重载是:
public static string Combine(string path1, string path2)
{
if (path1 == null || path2 == null)
{
throw new ArgumentNullException((path1 == null) ? "path1" : "path2");
}
Path.CheckInvalidPathChars(path1, false);
Path.CheckInvalidPathChars(path2, false);
return Path.CombineNoChecks(path1, path2);
}
优势显而易见;首先,该函数检查空值并抛出相应的异常。然后它检查任一参数中的非法字符,并抛出适当的异常。一旦满足,它就会调用Path.CombineNoChecks:
private static string CombineNoChecks(string path1, string path2)
{
if (path2.Length == 0)
{
return path1;
}
if (path1.Length == 0)
{
return path2;
}
if (Path.IsPathRooted(path2))
{
return path2;
}
char c = path1[path1.Length - 1];
if (c != Path.DirectorySeparatorChar && c != Path.AltDirectorySeparatorChar && c != Path.VolumeSeparatorChar)
{
return path1 + Path.DirectorySeparatorChar + path2;
}
return path1 + path2;
}
这里最有趣的是它支持的角色;
Path.DirectorySeparatorChar = "\\"
Path.AltDirectorySeparatorChar = "/"
Path.VolumeSeparatorChar = ":"
所以它也会支持分隔符错误的路径(例如来自urn file://C:/blah
)
简而言之,它更好,因为它为您提供验证,一定程度的可移植性(上面显示的3个常量可以在每个框架-OS的基础上定义),并且支持您经常遇到的多种类型的路径
答案 1 :(得分:2)
尝试这两个以查看差异....它可以处理URI和标准路径。所以请始终使用Path.Combine
。
Console.WriteLine(Path.Combine(@"file:///c:/temp/", "x.xml"));
输出file:///c:/temp/x.xml
Console.WriteLine(Path.Combine(@"C:\test", "x.xml"));
输出C:\test\x.xml
答案 2 :(得分:1)
是的,在文件路径分隔符与\
答案 3 :(得分:0)
首先,您可以使用此注释@"\file.txt
代替"\\file.txt";
其次,让.Net关心修复路径。我们有这个理由。 你可以100%确定你已经正确地完成了它,但是如果你开始在代码中的任何地方手动组合路径,总会有机会创建错误。
一个简单的例子。
temp
的子文件夹。你会做什么?如果最后没有反斜杠,请添加一个,否则执行此操作,否则执行其他操作...等。
使用Path.Combine()
,您无需进行检查。您可以专注于应用程序的实际逻辑。
答案 4 :(得分:0)
除了其他注释之外,还有其他注释,它是组合您要创建的目录的许多部分的功能。
这是一个例子:
Path.Combine(root, nextFolder, childfolder, file);
它支持许多字符,因为它接收一个字符串数组,因此它能够在一个执行的行中创建正确的目录。
此致