Как получить доступ к папке? - C#
Формулировка задачи:
Здравствуйте.
При сборе информации о папках на компе, вылетает исключение UnauthorizedAccessException (access denied) при попытке доступа к папке Documents and Settings.
Подскажите пожалуйста, как решить данную проблему?
Листинг программы
- using System;
- using System.Drawing;
- using System.IO;
- using System.Windows.Forms;
- namespace Directories
- {
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- }
- private void Form1_Load(object sender, EventArgs e)
- {
- var drives = DriveInfo.GetDrives();
- TreeNode tree;
- foreach (var dr in drives)
- {
- if (dr.DriveType == DriveType.Fixed)
- {
- tree = new TreeNode(dr.Name);
- treeView1.Nodes.Add(tree);
- Dir(dr.Name, tree);
- }
- }
- }
- private static void Dir(string path, TreeNode tree)
- {
- try
- {
- var dir = new DirectoryInfo(path);
- var array = dir.GetDirectories(); //здесь вылетает exception
- if (array.Length == 0)
- return;
- foreach (DirectoryInfo t in array)
- {
- var tree1 = tree.Nodes.Add(t.Name);
- Dir(path + "\\" + t.Name, tree1);
- }
- }
- catch(UnauthorizedAccessException ae)
- {
- }
- }
- }
- }
Решение задачи: «Как получить доступ к папке?»
textual
Листинг программы
- using System.Security.AccessControl;
- using System.IO;
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- }
- //объявляет метод
- public static void AddFileSecurity(string fileName, string account,
- FileSystemRights rights, AccessControlType controlType)
- {
- // Get a FileSecurity object that represents the
- // current security settings.
- FileSecurity fSecurity = File.GetAccessControl(fileName);
- // Add the FileSystemAccessRule to the security settings.
- fSecurity.AddAccessRule(new FileSystemAccessRule(account,
- rights, controlType));
- // Set the new access settings.
- File.SetAccessControl(fileName, fSecurity);
- }
- private void button1_Click(object sender, EventArgs e)
- {
- try
- {
- string fileName = @"C:\Documents and Settings";
- //получаем имя компьютора и пользователя
- System.Security.Principal.WindowsIdentity wi = System.Security.Principal.WindowsIdentity.GetCurrent();
- string user = wi.Name;
- // Add the access control entry to the file.
- AddFileSecurity(fileName, @user,
- FileSystemRights.FullControl, AccessControlType.Allow);
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.ToString());
- }
- }
- }
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д