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

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

    Here is a quick implementation that just loops through the list of strings and then compares the characters at the beginning of the strings trimming from the original string:

    List list1 = new List();
    list1.Add(@"c:\abc\pqr\tmp\sample\b.txt");
    list1.Add(@"c:\abc\pqr\tmp\new2\c1.txt");
    list1.Add(@"c:\abc\pqr\tmp\b2.txt");
    list1.Add(@"c:\abc\pqr\tmp\b3.txt");
    list1.Add(@"c:\abc\pqr\tmp\tmp2\b2.txt");
    
    string baseDir = "";
    foreach (var item in list1)
    {
        if (baseDir == "")
            baseDir = System.IO.Path.GetDirectoryName(item);
        else
        {
            int index = 0;
            string nextDir = System.IO.Path.GetDirectoryName(item);
            while (index< baseDir.Length && index

提交回复
热议问题