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.
FileIOPermission writePermission = new FileIOPermission(FileIOPermissionAccess.Write, filename);
if (SecurityManager.IsGranted(writePermission)){
//write here
} else {
//some error message
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With