how to extract common file path from list of file paths in c#

后端 未结 9 1454
粉色の甜心
粉色の甜心 2021-01-17 15:42

What is the best way extract the common file path from the list of file path strings in c#?

Eg: I have a list 5 file paths in List variable, like below

c:\

9条回答
  •  盖世英雄少女心
    2021-01-17 16:28

    Keep a tally of each segment and keep going while all the paths start with the tally.

    void Main()
    {
        string[] paths = new[] { @"c:\abc\pqr\tmp\sample\b.txt",
                                @"c:\abc\pqr\tmp\new2\c1.txt",
                                @"c:\abc\pqr\tmp\b2.txt",
                                @"c:\abc\pqr\tmp\b3.txt",
                                @"c:\abc\pqr\tmp\tmp2\b2.txt"};
    
        var test = new List();
        var common = paths[0].Split('\\').TakeWhile ( segment => 
        {
            test.Add ( segment );
            return paths.All ( path => path.StartsWith ( String.Join ("\\", test )  + "\\") ) ;
        } );
    
        Console.WriteLine ( String.Join ("\\", common ) );
    }
    

提交回复
热议问题