What is the advantage of using Path.Combine over concatenating strings with '+'?

后端 未结 5 466
情深已故
情深已故 2020-11-30 10:53

I don\'t quite see the difference.

What could Path.Combine do better than perfectly working string concatenation?

I guess it\'s doing something

相关标签:
5条回答
  • 2020-11-30 11:22

    Path.Combine does more things than just a string concatenation. If you look at the source code;

    • Checks both paths has invalid character or not
    • Checks second parameter is root path or not
    • Checks last character of first path is director or alt directory or volume separator or not. If not, concatenate both string with directory separator between then
    0 讨论(0)
  • 2020-11-30 11:27

    Path.Combine uses the Path.PathSeparator and it checks whether the first path has already a separator at the end so it will not duplicate the separators. Additionally, it checks whether the path elements to combine have invalid chars.

    0 讨论(0)
  • 2020-11-30 11:28

    According to this documentation Path.Combine internally performs a string concatenation using +-Operator.

     private static String CombineNoChecks(String path1, String path2) {
            if (path2.Length == 0)
                return path1;
    
            if (path1.Length == 0)
                return path2;
    
            if (IsPathRooted(path2))
                return path2;
    
            char ch = path1[path1.Length - 1];
            if (ch != DirectorySeparatorChar && ch != AltDirectorySeparatorChar && ch != VolumeSeparatorChar) 
                return path1 + DirectorySeparatorCharAsString + path2;
            return path1 + path2;
        }
    
    0 讨论(0)
  • 2020-11-30 11:41

    You avoid double path separators. If one path element already has a leading backslash. Path.Combine checks for that and ensures that only one backslash is present.

    0 讨论(0)
  • 2020-11-30 11:42

    Here is the implementation

    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);
    }
    
    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;
    }
    
    0 讨论(0)
提交回复
热议问题