In .NET, check that the current user may write to

2019-04-06 20:41发布

问题:

In .NET, is there a simple way to check whether the current user has access to create a file in a directory? Something equivalent to the C++ _access function, would be ideal.

I don't want to use trial and error (create a dummy file and then delete it): apart from seeming hackish, other software is monitoring the directory in question for dropped files.

I don't want to use System.DirectoryServices: looking at ACL's, resolving group memberships and how permissions from different group memberships interact seems error prone and too hard. There must be a yeah-or-nay function somewhere, no?

Thanks in advance!

[edit] as a bonus, if it would work for a network share as well, that'd be cool.

回答1:

FileIOPermission writePermission = new FileIOPermission(FileIOPermissionAccess.Write, filename);
if (SecurityManager.IsGranted(writePermission)){
    //write here
} else {
    //some error message
}


回答2:

Checking for permission in advance is a dicey project. Not to mention complicated, running through the entire ACL list and computing the effective permission set.

Further...there are no guarantees. Just because you proactively checked for permission ahead of time doesn't mean that the permissions won't have changed at the moment you try to create the file.

The "right" way is to make a security demand, either declaratively with FileIOPermissionAttribute or imperatively, by creating an appropriate instance of FileIOPermission and invoking its Demand() method. If you have the desired permissions, the call to Demand() succeeds; otherwise it throws a SecurityException, which you'll need to catch and act on.

In my experience, the imperative check is easier.

It should also be noted that in Windows 7, while you might conceptually have write access to the directory, it still might not work unless you're running with elevated permissions.



回答3:

The following will return a DirecotrySecurity instance http://msdn.microsoft.com/en-us/library/system.security.accesscontrol.directorysecurity.aspx

DirectoryInfo(pathstr).GetAccessControl()