目录与路径存在联合VS字符串连接 [英] Directory Exists with Path Combine vs String Concatenation

查看:193
本文介绍了目录与路径存在联合VS字符串连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以当我建立一个文件夹/文件检查的条件,和同事说,这是更好使用Path.Combine:

So as I am building a Folder/File checking conditional, and a co-worker says it is "better" to use Path.Combine:

string finalPath = Path.Combine(folder, "file.txt"); 



,而不是我是用

as opposed to the way I was doing it with

string finalPath = folder +  "\\file.txt";



任何声音的推理,这是更好?

Any sound reasoning this is "better?"

推荐答案

这是一个有趣的问题;

It's an interesting question;

您当然可以,写的是这样的:

You could, of course, write something like:

string finalPath = String.Format("{0}\\file.txt", folder); 

要达到你想要的结果。

使用 ILSpy ,不过,让我们看看为什么的 Path.Combine 是更好的。

Using ILSpy, though, lets see why Path.Combine is better.

您呼叫的过载是:

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:

The advantages are obvious; firstly, the function checks for null values and throws the appropriate exception. Then it checks for illegal characters in either of the arguments, and throws an appropriate exception. Once it is satisfied, it calls 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;
}



在这里最有趣的事情是它支持的字符;

The most interesting thing here are the characters it supports;

Path.DirectorySeparatorChar = "\\"
Path.AltDirectorySeparatorChar = "/"
Path.VolumeSeparatorChar = ":"

所以它也将支持路径,其中分隔符是各地(如错误的方式从瓮文件:// C:/等等,太)

So it will also support paths where the separator is the wrong way around (like from a urn file://C:/blah, too)

在总之,这是更好,因为它给你验证,一可移植性的程度(上面显示的3常量可以在每个框架-OS为基础定义),并且具有一个以上的类型时通常遇到的路径的支持

In short, it's better because it gives you validation, a degree of portability (the 3 constants shown above can be defined on a per framework-OS basis), and has support for more than one type of path that you commonly encounter.

这篇关于目录与路径存在联合VS字符串连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆