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

血红的双手。 提交于 2020-01-01 09:04:33

问题


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()


来源:https://stackoverflow.com/questions/8842034/in-net-check-that-the-current-user-may-write-to-a-directory

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!