Question

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...

Was it helpful?

Solution

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
}

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top