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

前端 未结 3 1699
孤城傲影
孤城傲影 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:17

    If you already have an array or an IEnumerable then you could do this in one line...

    // I'm assuming that you've got an array or IEnumerable from somewhere
    var paths = new string[] { path1, path2, path3, path4, path5, path6 };
    
    string result = paths.Aggregate(Path.Combine);
    

    If not, then write your own extension method to string...

    public static class PathExtension
    {
        public static string CombinePathWith(this string path1, string path2)
        {
            return Path.Combine(path1, path2);
        }
    }
    

    ... that would allow you to chain these like this...

    string result = path1.CombinePathWith(path2)
                         .CombinePathWith(path3)
                         .CombinePathWith(path4)
                         .CombinePathWith(path5)
                         .CombinePathWith(path6);
    

提交回复
热议问题