How can Path.Combine be used with more than two arguments?

前端 未结 3 1700
孤城傲影
孤城傲影 2021-02-18 14:02

I\'m surprised there\'s not an overload that can take a string array. Anyway, what is the best way to avoid nesting calls to Path.Combine?

pathValue = Path.Combi         


        
3条回答
  •  难免孤独
    2021-02-18 14:14

    It's pretty straightforward to implement it yourself:

    public string Combine(params string[] paths)
    {
        char[] pathSeparators = new char[] 
            { Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar, Path.VolumeSeparatorChar };
    
        if(paths == null) throw new ArgumentNullException("paths");
        if(paths.Length == 1) return paths[0];
    
        StringBuilder pathBuilder = new StringBuilder();
    
        foreach(string path in paths)
        {
            if(Path.IsPathRooted(path))
                pathBuilder = new StringBuilder(path);
            else
            {
                char last = pathBuilder.Length > 0 ?
                    pathBuilder[pathBuilder.Length - 1] :
                    path[path.Length - 1];
    
                if(Array.IndexOf(pathSeparators, last) == -1)
                    pathBuilder.Append(Path.DirectorySeparatorChar);
    
                pathBuilder.Append(path);
            } // else
        } // foreach
    
        return pathBuilder.ToString();
    }
    
    [Test()]
    public void CombinePaths()
    {
        string result = Combine(@"C:\Program Files\", @"Microsoft.NET", @"ADOMD.NET\", "90", "msadomdx.dll");
        Assert.AreEqual(@"C:\Program Files\Microsoft.NET\ADOMD.NET\90\msadomdx.dll", result);
    }
    

提交回复
热议问题