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

后端 未结 9 1458
粉色の甜心
粉色の甜心 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:07

    The top answer fails for identical paths like e.g.:

    string str1 = @"c:\dir\dir1\dir2\dir3";
    string str2 = @"c:\dir\dir1\dir2\dir3";
    

    This is better: Find common prefix of strings

    however

    .TakeWhile(s => s.All(d => d == s.First()))
    

    should be

    .TakeWhile(s =>
          {
              var reference = s.First();
              return s.All(d => string.Equals(reference, d, StringComparison.OrdinalIgnoreCase));
          })
    

提交回复
热议问题