Search code examples
c#.netwinformsaccess-rights

Restricting access to certain folders with a FolderBrowserDialog


I want to restrict what folder a person can choose to set their default save path in my app. Is there a class or method which would allow me to check access rights and either limit the user's options or show an error once they have made their selection. Is FileSystemSecurity.AccessRightType a possibility?


Solution

  • Since the FolderBrowserDialog is a rather closed control (it opens a modal dialog, does it stuff, and lets you know what the user picked), I don't think you're going to have much luck intercepting what the user can select or see. You could always make your own custom control, of course ;)

    As for testing if they have access to a folder

    private void OnHandlingSomeEvent(object sender, EventArgs e)
    {
      DialogResult result = folderBrowserDialog1.ShowDialog();
      if(result == DialogResult.OK)
      {
          String folderPath = folderBrowserDialog1.SelectedPath;
          if (UserHasAccess(folderPath)) 
          {
            // yay! you'd obviously do something for the else part here too...
          }
      }
    }
    
    private bool UserHasAccess(String folderPath)
    {
      try
      {
        // Attempt to get a list of security permissions from the folder. 
        // This will raise an exception if the path is read only or do not have access to view the permissions. 
        System.Security.AccessControl.DirectorySecurity ds =
          System.IO.Directory.GetAccessControl(folderPath);
        return true;
      }
      catch (UnauthorizedAccessException)
      {
        return false;
      }
    }
    

    I should note that the UserHasAccess function stuff was obtained from this other StackOverflow question.