我同意GSerg。只是为了增加一些额外的火力,我将添加以下使用 Reflector 获得的代码片段。
Directory.GetParent 函数基本上只是调用 Path.GetDirectoryName 函数:
[SecuritySafeCritical]
public static DirectoryInfo GetParent(string path)
{
if (path == null)
{
throw new ArgumentNullException("path");
}
if (path.Length == 0)
{
throw new ArgumentException(Environment.GetResourceString("Argument_PathEmpty"), "path");
}
string directoryName = Path.GetDirectoryName(Path.GetFullPathInternal(path));
if (directoryName == null)
{
return null;
}
return new DirectoryInfo(directoryName);
}
DirectoryInfo 的 Parent 属性基本上去掉了一个斜杠,然后调用 Path.GetDirectoryName:
public DirectoryInfo Parent
{
[SecuritySafeCritical]
get
{
string fullPath = base.FullPath;
if ((fullPath.Length > 3) && fullPath.EndsWith(Path.DirectorySeparatorChar))
{
fullPath = base.FullPath.Substring(0, base.FullPath.Length - 1);
}
string directoryName = Path.GetDirectoryName(fullPath);
if (directoryName == null)
{
return null;
}
DirectoryInfo info = new DirectoryInfo(directoryName, false);
new FileIOPermission(FileIOPermissionAccess.PathDiscovery | FileIOPermissionAccess.Read, info.demandDir, false, false).Demand();
return info;
}
}