Как получить доступ к папке? - C#

Узнай цену своей работы

Формулировка задачи:

Здравствуйте. При сборе информации о папках на компе, вылетает исключение UnauthorizedAccessException (access denied) при попытке доступа к папке Documents and Settings. Подскажите пожалуйста, как решить данную проблему?
Листинг программы
  1. using System;
  2. using System.Drawing;
  3. using System.IO;
  4. using System.Windows.Forms;
  5. namespace Directories
  6. {
  7. public partial class Form1 : Form
  8. {
  9. public Form1()
  10. {
  11. InitializeComponent();
  12. }
  13. private void Form1_Load(object sender, EventArgs e)
  14. {
  15. var drives = DriveInfo.GetDrives();
  16. TreeNode tree;
  17. foreach (var dr in drives)
  18. {
  19. if (dr.DriveType == DriveType.Fixed)
  20. {
  21. tree = new TreeNode(dr.Name);
  22. treeView1.Nodes.Add(tree);
  23. Dir(dr.Name, tree);
  24. }
  25. }
  26. }
  27. private static void Dir(string path, TreeNode tree)
  28. {
  29. try
  30. {
  31. var dir = new DirectoryInfo(path);
  32. var array = dir.GetDirectories(); //здесь вылетает exception
  33. if (array.Length == 0)
  34. return;
  35. foreach (DirectoryInfo t in array)
  36. {
  37. var tree1 = tree.Nodes.Add(t.Name);
  38. Dir(path + "\\" + t.Name, tree1);
  39. }
  40. }
  41. catch(UnauthorizedAccessException ae)
  42. {
  43. }
  44. }
  45. }
  46. }

Решение задачи: «Как получить доступ к папке?»

textual
Листинг программы
  1. using System.Security.AccessControl;
  2.     using System.IO;
  3.     public partial class Form1 : Form
  4.     {
  5.         public Form1()
  6.         {
  7.             InitializeComponent();
  8.         }
  9.         //объявляет метод
  10.         public static void AddFileSecurity(string fileName, string account,
  11.           FileSystemRights rights, AccessControlType controlType)
  12.         {
  13.  
  14.             // Get a FileSecurity object that represents the
  15.             // current security settings.
  16.             FileSecurity fSecurity = File.GetAccessControl(fileName);
  17.  
  18.             // Add the FileSystemAccessRule to the security settings.
  19.             fSecurity.AddAccessRule(new FileSystemAccessRule(account,
  20.                 rights, controlType));
  21.  
  22.             // Set the new access settings.
  23.             File.SetAccessControl(fileName, fSecurity);
  24.  
  25.         }
  26.        
  27.         private void button1_Click(object sender, EventArgs e)
  28.         {
  29.             try
  30.             {
  31.  
  32.                 string fileName = @"C:\Documents and Settings";
  33.  
  34.                 //получаем имя компьютора и пользователя
  35.                 System.Security.Principal.WindowsIdentity wi = System.Security.Principal.WindowsIdentity.GetCurrent();
  36.                 string user = wi.Name;
  37.  
  38.                 // Add the access control entry to the file.
  39.                 AddFileSecurity(fileName, @user,
  40.                     FileSystemRights.FullControl, AccessControlType.Allow);
  41.  
  42.                
  43.  
  44.             }
  45.             catch (Exception ex)
  46.             {
  47.                 MessageBox.Show(ex.ToString());
  48.             }
  49.  
  50.         }
  51.     }

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

5   голосов , оценка 3.6 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут
Похожие ответы