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:\
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
}