Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 943
Craig Celeste Avatar asked Jan 12 '12 20:01

Craig Celeste


2 Answers

FileIOPermission writePermission = new FileIOPermission(FileIOPermissionAccess.Write, filename);
if (SecurityManager.IsGranted(writePermission)){
    //write here
} else {
    //some error message
}
like image 128
KevinA Avatar answered Oct 23 '22 15:10

KevinA


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.

like image 33
Nicholas Carey Avatar answered Oct 23 '22 15:10

Nicholas Carey