public static class FileSystemInfoExtender
{
public static string GetPathRelativeTo(this FileSystemInfo file, string path)
{
string fullPath = Path.GetFullPath(path);
string res = string.Empty;
if (file.FullName.StartsWith(fullPath))
{
res = file.FullName.Substring(fullPath.Length);
}
res = res.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
string sep = Path.DirectorySeparatorChar.ToString();
if (res.StartsWith(sep))
{
res = res.Substring(1);
}
return res;
}
}
and some tests
FileInfo file = new FileInfo(@"D:\Projects\smeg\src\blah\xxxx\whistle\stop\Carbuncle.cs");
string relPath = file.GetPathRelativeTo(@"D:\Projects\smeg\src");
Debug.Assert(relPath.Equals(@"blah\xxxx\whistle\stop\Carbuncle.cs",
StringComparison.OrdinalIgnoreCase));
relPath = file.GetPathRelativeTo(@"D:/Projects/smeg/src");
Debug.Assert(relPath.Equals(@"blah\xxxx\whistle\stop\Carbuncle.cs",
StringComparison.OrdinalIgnoreCase));
relPath = file.GetPathRelativeTo(@"D:\Projects\smeg\src\");
Debug.Assert(relPath.Equals(@"blah\xxxx\whistle\stop\Carbuncle.cs",
StringComparison.OrdinalIgnoreCase));
No comments:
Post a Comment