Search code examples
c#permissionsc#-2.0

Checking for shared folder write access for current user


I have following method to check current user have write access to given network location

DirectorySecurity shareSecurity = new DirectoryInfo(this.GetFileServerRootPath).GetAccessControl();

foreach (FileSystemAccessRule fsRule in shareSecurity.GetAccessRules(true, true, typeof(NTAccount)))
{
    // check write permission for current user
    if (AccessControlType.Allow == fsRule.AccessControlType &&
            FileSystemRights.Write == (fsRule.FileSystemRights & FileSystemRights.Write))
    {
        if (null != fsRule.IdentityReference &&
            fsRule.IdentityReference.Value == WindowsIdentity.GetCurrent().Name)
        {
            return true;
        }
    }
}
return false;

but problem is when folder permission given to user group, above method is failed.

I don't want to check the permissions by writing a file and decide the write access permissions.

is there any way to find current user in the IdentityReference.Value? or suggestions to overcome this issue?


Solution

  • This may work for you:

    FileIOPermission writePermission = new FileIOPermission(FileIOPermissionAccess.Write, this.GetFileServerRootPath);
    
    try
    {
        writePermission.Demand();
        return true;
    }
    catch (SecurityException s)
    {
        return false;
    }
    

    Just curious - why not just try/catch your write operation?