I have two paths: 'C:\ol\il\ek' and 'ek\mek\gr'. How can i cut the common part from these paths? I'm making one paths from them like that (h- first path, n - second path):
ee.Load(h + "\\" + n);
I have two paths: 'C:\ol\il\ek' and 'ek\mek\gr'. How can i cut the common part from these paths? I'm making one paths from them like that (h- first path, n - second path):
ee.Load(h + "\\" + n);
Assuming the "common part" is always the last segment of the first path, and the first segment of the second one, you can use Path.GetDirectoryName to strip this segment from the first path and combine the result with the second path using Path.Combine:
var result = Path.Combine(Path.GetDirectoryName(@"C:\ol\il\ek"), @"ek\mek\gr");
// result == @"C:\ol\il\ek\mek\gr"
I wrote following class, that I think could meet your needs. First I split paths in single directory parts. Than I check last parts of path1 with first of path2, increasing num of parts I compare, until I reach parts limit or get equal parts. When I found equal parts in the two paths, I clear path2 parts.
static class Program
{
static void Main(string[] args)
{
Console.WriteLine(JoinPaths(@"C:\ol\il\ek", @"ek\mek\gr"));
Console.WriteLine(JoinPaths(@"C:\ol\il\ek", @"il\ek\mek\gr"));
Console.WriteLine(JoinPaths(@"C:\ol\il\ek", @"ol\il\ek\mek\gr"));
Console.ReadLine();
}
public static T[] Slice<T>(this T[] source, int start, int end)
{
if (end < 0)
end = source.Length + end;
var len = end - start;
var res = new T[len];
for (var i = 0; i < len; i++)
res[i] = source[i + start];
return res;
}
private static string JoinPaths(string path1, string path2)
{
var parts1 = path1.ToLower().Split(new char[] { '\\' });
var parts2 = path2.ToLower().Split(new char[] { '\\' });
int commonPartLen = 1;
while (commonPartLen<parts1.Length && commonPartLen<parts2.Length)
{
string slice1 = string.Join("\\", parts1.Slice(parts1.Length - commonPartLen, parts1.Length ));
string slice2 = string.Join("\\", parts2.Slice(0, commonPartLen));
if (slice1 == slice2)
{
for (var i = 0; i < commonPartLen; i++)
parts2[i] = "";
break;
}
commonPartLen++;
}
string firstPath = string.Join("\\", parts1.Where(a => !string.IsNullOrEmpty(a)));
string secondPath = string.Join("\\", parts2.Where(a => !string.IsNullOrEmpty(a)));
return firstPath + "\\"+secondPath; ;
}
}
I hope the code is clear.