Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

.net

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

like image 949
weiqure Avatar asked Feb 28 '23 20:02

weiqure


2 Answers

You can use FileIOPermission to determine if your application has particular permissions for a 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 repsonse to your question could be something like :

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
}
like image 117
PaulB Avatar answered May 09 '23 22:05

PaulB


Just try to create the folder and catch the ensuing exception: everything else isn't safe because since Windows is (more or less) a real-time systen, between the moment where you test for the rights and the moment of folder creation, the rights might have been changed. Consider the following potential, critical event chain:

  • User is about to change the folder rights
  • Application tests for folder creation rights: test for rights successful
  • User commits the changes
  • Application tries to create the folder
like image 39
Konrad Rudolph Avatar answered May 09 '23 20:05

Konrad Rudolph