0

Any way to check if write permissions are available on a given path that could be either a local folder (c:\temp) or a UNC (\server\share)? I can't use try/catch because I might have write permissions but not delete so I wouldn't be able to delete created file...

Bob Lotz
  • 85
  • 1
  • 10
  • Permissions can change during the time that your application is running. Or the network could go down after write but before delete. You have to work out how to deal with those situations *anyway* - why write more code? – Damien_The_Unbeliever Mar 12 '13 at 18:02

2 Answers2

3

You use a permissions demand, thus:

FileIOPermission f2 = new FileIOPermission(FileIOPermissionAccess.Read, "C:\\test_r");
f2.AddPathList(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, "C:\\example\\out.txt");
try
{
  f2.Demand();
  // do something useful with the file here
}
catch (SecurityException s)
{
  Console.WriteLine(s.Message);
  // deal with the lack of permissions here.
}

specifying the permissions you want and the file system object(s) desired. If you don't have the demanded permission, a Security exception is thrown. More details at

For a variety of reasons — race conditions being one of them — it's more complicated than it might seem to examine NTFS file system permissions.

Apparently, we figured out a while back that this is a no-op for UNC paths. See this question, Testing a UNC Path's "Accessability", for detials.

A little google-fu suggests that this CodeProject class might be of use, though: http://www.codeproject.com/Articles/14402/Testing-File-Access-Rights-in-NET-2-0

Community
  • 1
  • 1
Nicholas Carey
  • 71,308
  • 16
  • 93
  • 135
  • Neither solution worked for UNC. I have a UNC path that has Read access but not Write. If I pass that path to the code above both return positive for Write. – Bob Lotz Mar 12 '13 at 19:21
  • Yes...apparently, we figured out a couple years ago that that is the case :D -- http://stackoverflow.com/questions/5732347/testing-a-unc-paths-accessability. Looks like you need look at the ACL for it directly. This might work: http://www.codeproject.com/Articles/14402/Testing-File-Access-Rights-in-NET-2-0. I've amended my answer to reflect the same. – Nicholas Carey Mar 12 '13 at 21:34
  • Appreciate your help but that didn't work either... I'll have to improvise I guess. – Bob Lotz Mar 13 '13 at 17:52
3

Yes you can use the FileIOPermission class and the FileIOPermissionAccess enum.

FileIOPermissionAccess.Write:

Access to write to or delete a file or directory. Write access includes deleting and overwriting files or directories.


FileIOPermission f = new FileIOPermission(FileIOPermissionAccess.Write, myPath);

try
{
   f.Demand();
   //permission to write/delete/overwrite
}
catch (SecurityException s)
{
   //there is no permission to write/delete/overwrite
}
Omar
  • 16,329
  • 10
  • 48
  • 66