Bug in Directory.GetParent?

后端 未结 3 1334
天命终不由人
天命终不由人 2020-12-11 02:10

I was hit in the face by a very weird behavior of the System.IO.Directory.GetParent method:

string path1 = @\"C:\\foo\\bar\";
DirectoryInfo pare         


        
3条回答
  •  青春惊慌失措
    2020-12-11 02:38

    I agree with GSerg. Just to add some additional firepower, I'm going to add the following code snippets obtained with Reflector.

    The Directory.GetParent function basically just calls the Path.GetDirectoryName function:

    [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);
    }
    

    The Parent property of the DirectoryInfo basically strips off a trailing slash and then calls 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;
        }
    }
    

提交回复
热议问题