Отказано в доступе по пути на удаление файла - C#
Формулировка задачи:
Возникла проблема с правами на удаление jpg файлов из папки на рабочем столе, пишет "отказано в доступе по пути":
Можно ли как то обойти права? Запуск от имени не вариант. ОС Windows 7
string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\1\";
string[] delJPG = Directory.GetFiles(desktop, "*.jpg");
foreach (var item in delJPG)
{
File.Delete(desktop);
}Решение задачи: «Отказано в доступе по пути на удаление файла»
textual
Листинг программы
using System.Security.AccessControl;
using System.IO;
.................................................
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)
{
bool b = false;
string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\1\";
try
{
//получаем имя компьютора и пользователя
System.Security.Principal.WindowsIdentity wi = System.Security.Principal.WindowsIdentity.GetCurrent();
string user = wi.Name;
// Add the access control entry to the file.
AddFileSecurity(desktop, @user,
FileSystemRights.FullControl, AccessControlType.Allow);
b = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
if (b)
{
string[] delJPG = Directory.GetFiles(desktop, "*.jpg");
foreach (var item in delJPG)
{
File.Delete(desktop);
}
}
}