且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查是否在Windows文件是可读/写?

更新时间:2023-11-25 16:47:22

好了,这是我最后绕了:

Well, here's what I eventually wound up with:

    private readonly static WindowsIdentity _identity = WindowsIdentity.GetCurrent();
    protected static bool GetPermission(FileSystemRights right, string path)
    {
        FileSecurity fs;
        try
        {
            fs = System.IO.File.GetAccessControl(path);
        }
        catch(InvalidOperationException)
        {
            // called on a disk that's not present, ...
            return false;
        }
        catch(UnauthorizedAccessException)
        {
            return false;
        }
        foreach(FileSystemAccessRule fsar in fs.GetAccessRules(true, true, typeof(SecurityIdentifier)))
        {
            if(fsar.IdentityReference == _identity.User && fsar.FileSystemRights.HasFlag(right) && fsar.AccessControlType == AccessControlType.Allow)
            {
                return true;
            }
            else if(_identity.Groups.Contains(fsar.IdentityReference) && fsar.FileSystemRights.HasFlag(right) && fsar.AccessControlType == AccessControlType.Allow)
            {
                return true;
            }
        }
        return false;
    }

当然,这不是理想的,因为它忽视了拒绝的权利。但我不知道以何种顺序应用不同的ACE(我想?)为了找出正确的能力。不过,拒绝规则是比较罕见的,所以它的工作大部分时间我。

Of course, it's not ideal, because it ignores Deny rights. But I have no idea in which order to apply the various ACEs (I think?) in order to find out the "correct" ability. Still, Deny rules are relatively rare, so it works most of the time for me.