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

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

    I would use a loop and on each string I'd split it with s.Split('\').

    Then it iterate over the first element, and next element, saving them as I go.

    When I find one that is different, I can return the last iteration's result.

    string commonPath(string[] paths) {
        // this is a Java notation, I hope it's right in C# as well? Let me know!
        string[][] tokens = new string[paths.length][];
    
        for(int i = 0; i < paths.Length; i++) {
            tokens[i] = paths.Split('\\');
        }
    
        string path = "";
    
        for(int i = 0; i < tokens[0].Length; i++) {
            string current = tokens[0][i];
            for(int j = 1; j < tokens.Length; j++) {
                if(j >= tokens[i].Length) return path;
                if(current != tokens[i][j]) return path;
            }
            path = path + current + '\\';
        }
        return path; // shouldn't reach here, but possible on corner cases
    }
    

提交回复
热议问题