public static class FileSystemInfoExtensions
{
public static bool HasParent(this DirectoryInfo directInfo, DirectoryInfo parentDirectInfo)
{
return FileSystemInfoHasParent(directInfo.Parent, parentDirectInfo);
}
public static bool HasParent(this FileInfo fInfo, DirectoryInfo parentDirectInfo)
{
return FileSystemInfoHasParent(fInfo.Directory, parentDirectInfo);
}
private static bool FileSystemInfoHasParent(DirectoryInfo thisParentDirectInfo, DirectoryInfo parentDirectInfo)
{
string parent = parentDirectInfo.FullName.TrimEnd(Path.DirectorySeparatorChar);
while (thisParentDirectInfo != null)
{
if (thisParentDirectInfo.FullName.Equals(parent, StringComparison.InvariantCultureIgnoreCase))
{
return true;
}
thisParentDirectInfo = thisParentDirectInfo.Parent;
}
return false;
}
public static string GetRelativePathTo(this FileSystemInfo fromPath, FileSystemInfo toPath)
{
int fromAttr = GetPathAttribute(fromPath);
int toAttr = GetPathAttribute(toPath);
StringBuilder path
= new StringBuilder
(260); // MAX_PATH if (PathRelativePathTo(
path,
fromPath.FullName,
fromAttr,
toPath.FullName,
toAttr) == 0)
{
throw new ArgumentException
("Paths must have a common prefix"); }
return path.ToString();
}
public static string GetRelativePathTo(this FileSystemInfo fromPath, string toPath)
{
int fromAttr = GetPathAttribute(fromPath);
int toAttr = GetPathAttribute(toPath);
StringBuilder path
= new StringBuilder
(260); // MAX_PATH if (PathRelativePathTo(
path,
fromPath.FullName,
fromAttr,
toPath,
toAttr) == 0)
{
throw new ArgumentException
("Paths must have a common prefix"); }
return path.ToString();
}
private static int GetPathAttribute(FileSystemInfo path)
{
if (!path
.Exists) throw new FileNotFoundException
(); return String.IsNullOrEmpty(path.Extension) ? FILE_ATTRIBUTE_DIRECTORY : FILE_ATTRIBUTE_NORMAL;
}
private static int GetPathAttribute(string path)
{
DirectoryInfo di
= new DirectoryInfo
(path
); if (di.Exists)
{
return FILE_ATTRIBUTE_DIRECTORY;
}
FileInfo fi
= new FileInfo
(path
); if (fi.Exists)
{
return FILE_ATTRIBUTE_NORMAL;
}
throw new FileNotFoundException
(); }
private const int FILE_ATTRIBUTE_DIRECTORY = 0x10;
private const int FILE_ATTRIBUTE_NORMAL = 0x80;
[DllImport("shlwapi.dll", SetLastError = true)]
private static extern int PathRelativePathTo(StringBuilder pszPath,
string pszFrom, int dwAttrFrom, string pszTo, int dwAttrTo);
}