If you need to check that sufficient permissions exist to write to file or not.The following code example shows the use of the FileIOPermission(FileIOPermissionAccess, String) constructor to create a new instance of the FileIOPermission class with the write access to the C:\test.txt file, Write access includes deleting and overwriting files or directories. And then we can determine whether a write permission is granted or not with the help of SecurityManager.IsGranted() method.
//First method: string FileLocation = @"C:\test.txt"; FileIOPermission writePermission = new FileIOPermission( FileIOPermissionAccess.Write, FileLocation); if (SecurityManager.IsGranted(writePermission)) { // you have permission } else { // permission is required! }
The simplest way is try to access the directory and catch the UnauthorizedAccessException; if the exception was thrown the user does not have access.
// Second method try { // Write the code to check access file or directory } catch (UnauthorizedAccessException ex) { MessageBox.Show("permission is required!"); } catch (Exception ex1) { MessageBox.Show(ex1.Message); }