How can I find out if my program has the right to create a file in a directory?

If I have the right to create a new file in the program directory, I want to create a file there, if I do not want to create a file in the AppData folder of the program.

+4
source share
2 answers

Just try to create a folder and catch the following exception: everything else is unsafe, because Windows is a (more or less) real-time system, between the moment you check the rights and the moment the folder is created, the rights could be changed. Consider the following potential critical chain of events:

  • User is going to change folder permissions
  • Application Tests for Folder Creation Permissions: Verifying Permissions Successfully
  • User commits changes
  • The application is trying to create a folder
+1
source

You can use FileIOPermission to determine if your application has specific permissions for the file / folder.

From MSDN:

FileIOPermission f = new FileIOPermission(PermissionState.None); f.AllLocalFiles = FileIOPermissionAccess.Read; try { f.Demand(); } catch (SecurityException s) { Console.WriteLine(s.Message); } 

EDIT: A more explicit answer to your question might be something like this:

 private string GetWritableDirectory() { string currentDir = Environment.CurrentDirectory; // Get the current dir FileIOPermission f = new FileIOPermission(FileIOPermissionAccess.Write, currentDir); try { f.Demand(); // Check for write access } catch (SecurityException s) { return Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) ; // Return the appdata (you may want to pick a differenct folder here) } return currentDir; // Have write access to current dir } 
+7
source

All Articles