Ответ 1
Это совершенно правильный способ проверить доступ к папкам на С#. Единственное место, где он может упасть, - это если вам нужно вызвать это в узком цикле, где могут возникнуть проблемы с издержками исключения.
Мне нужно проверить, может ли пользователь писать в папку, прежде чем на самом деле попытаться это сделать.
Я реализовал следующий метод (в С# 2.0), который пытается получить разрешения безопасности для папки с помощью Directory.GetAccessControl() метод.
private bool hasWriteAccessToFolder(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 = Directory.GetAccessControl(folderPath);
return true;
}
catch (UnauthorizedAccessException)
{
return false;
}
}
Когда я работал в Google, чтобы проверить доступ к записи, ничего подобного не получилось, и оказалось, что очень сложно фактически протестировать разрешения в Windows. Я обеспокоен тем, что я чрезмерно упрощаю вещи и что этот метод не является надежным, хотя он, похоже, работает.
Будет ли мой метод проверяться, правильно ли работает текущий доступ для записи?
Это совершенно правильный способ проверить доступ к папкам на С#. Единственное место, где он может упасть, - это если вам нужно вызвать это в узком цикле, где могут возникнуть проблемы с издержками исключения.
Я ценю, что это немного поздно в день для этого сообщения, но вы можете найти этот бит кода полезным.
string path = @"c:\temp";
string NtAccountName = @"MyDomain\MyUserOrGroup";
DirectoryInfo di = new DirectoryInfo(path);
DirectorySecurity acl = di.GetAccessControl(AccessControlSections.All);
AuthorizationRuleCollection rules = acl.GetAccessRules(true, true, typeof(NTAccount));
//Go through the rules returned from the DirectorySecurity
foreach (AuthorizationRule rule in rules)
{
//If we find one that matches the identity we are looking for
if (rule.IdentityReference.Value.Equals(NtAccountName,StringComparison.CurrentCultureIgnoreCase))
{
//Cast to a FileSystemAccessRule to check for access rights
if ((((FileSystemAccessRule)rule).FileSystemRights & FileSystemRights.WriteData)>0)
{
Console.WriteLine(string.Format("{0} has write access to {1}", NtAccountName, path));
}
else
{
Console.WriteLine(string.Format("{0} does not have write access to {1}", NtAccountName, path));
}
}
}
Console.ReadLine();
Отбросьте это в консольное приложение и убедитесь, что он делает то, что вам нужно.
public bool IsDirectoryWritable(string dirPath, bool throwIfFails = false)
{
try
{
using (FileStream fs = File.Create(
Path.Combine(
dirPath,
Path.GetRandomFileName()
),
1,
FileOptions.DeleteOnClose)
)
{ }
return true;
}
catch
{
if (throwIfFails)
throw;
else
return false;
}
}
Например, для всех пользователей (Builtin\Users) этот метод работает нормально - наслаждайтесь.
public static bool HasFolderWritePermission(string destDir)
{
if(string.IsNullOrEmpty(destDir) || !Directory.Exists(destDir)) return false;
try
{
DirectorySecurity security = Directory.GetAccessControl(destDir);
SecurityIdentifier users = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
foreach(AuthorizationRule rule in security.GetAccessRules(true, true, typeof(SecurityIdentifier)))
{
if(rule.IdentityReference == users)
{
FileSystemAccessRule rights = ((FileSystemAccessRule)rule);
if(rights.AccessControlType == AccessControlType.Allow)
{
if(rights.FileSystemRights == (rights.FileSystemRights | FileSystemRights.Modify)) return true;
}
}
}
return false;
}
catch
{
return false;
}
}
Я пробовал большинство из них, но они дают ложные срабатывания, все по той же причине.. Недостаточно проверить каталог на доступное разрешение, вам нужно проверить, что зарегистрированный пользователь является членом группы у которого есть это разрешение. Для этого вы получаете идентификатор пользователей и проверяете, является ли он членом группы, содержащей идентификатор IdentityReference FileSystemAccessRule. Я проверил это, работает безупречно.
/// <summary>
/// Test a directory for create file access permissions
/// </summary>
/// <param name="DirectoryPath">Full path to directory </param>
/// <param name="AccessRight">File System right tested</param>
/// <returns>State [bool]</returns>
public static bool DirectoryHasPermission(string DirectoryPath, FileSystemRights AccessRight)
{
if (string.IsNullOrEmpty(DirectoryPath)) return false;
try
{
AuthorizationRuleCollection rules = Directory.GetAccessControl(DirectoryPath).GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));
WindowsIdentity identity = WindowsIdentity.GetCurrent();
foreach (FileSystemAccessRule rule in rules)
{
if (identity.Groups.Contains(rule.IdentityReference))
{
if ((AccessRight & rule.FileSystemRights) == AccessRight)
{
if (rule.AccessControlType == AccessControlType.Allow)
return true;
}
}
}
}
catch { }
return false;
}
IMHO единственный надежный способ проверки на 100%, если вы можете написать в каталог, - это фактически написать ему и в конечном итоге поймать исключения.
Попробуйте следующее:
try
{
DirectoryInfo di = new DirectoryInfo(path);
DirectorySecurity acl = di.GetAccessControl();
AuthorizationRuleCollection rules = acl.GetAccessRules(true, true, typeof(NTAccount));
WindowsIdentity currentUser = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(currentUser);
foreach (AuthorizationRule rule in rules)
{
FileSystemAccessRule fsAccessRule = rule as FileSystemAccessRule;
if (fsAccessRule == null)
continue;
if ((fsAccessRule.FileSystemRights & FileSystemRights.WriteData) > 0)
{
NTAccount ntAccount = rule.IdentityReference as NTAccount;
if (ntAccount == null)
{
continue;
}
if (principal.IsInRole(ntAccount.Value))
{
Console.WriteLine("Current user is in role of {0}, has write access", ntAccount.Value);
continue;
}
Console.WriteLine("Current user is not in role of {0}, does not have write access", ntAccount.Value);
}
}
}
catch (UnauthorizedAccessException)
{
Console.WriteLine("does not have write access");
}
Ваш код получает DirectorySecurity
для данного каталога и правильно обрабатывает исключение (из-за того, что у вас нет доступа к информации о безопасности). Однако в вашем примере вы фактически не запрашиваете возвращаемый объект, чтобы узнать, какой доступ разрешен, и я думаю, вам нужно добавить это.
Я использовал ту же функцию для проверки, есть ли файл hasWriteAccess:
private static bool HasWriteAccessToFile(string filePath)
{
try
{
// Attempt to get a list of security permissions from the file.
// This will raise an exception if the path is read only or do not have access to view the permissions.
File.GetAccessControl(filePath);
return true;
}
catch (UnauthorizedAccessException)
{
return false;
}
}
Ниже приведена измененная версия ответа CsabaS, в которой содержатся явные правила доступа к запрету. Функция проходит через все файлы FileSystemAccessRules для каталога и проверяет, имеет ли текущий пользователь роль, которая имеет доступ к каталогу. Если таких ролей не найдено или пользователь не выполняет роль с запрещенным доступом, функция возвращает false. Чтобы проверить права на чтение, пройдите FileSystemRights.Read к функции; для права на запись, передайте FileSystemRights.Write. Если вы хотите проверить произвольные права пользователя, а не текущие, замените currentUser WindowsIdentity на требуемый идентификатор WindowsIdentity. Я бы также посоветовал не полагаться на такие функции, чтобы определить, может ли пользователь безопасно использовать каталог. Этот ответ прекрасно объясняет, почему.
public static bool UserHasDirectoryAccessRights(string path, FileSystemRights accessRights)
{
var isInRoleWithAccess = false;
try
{
var di = new DirectoryInfo(path);
var acl = di.GetAccessControl();
var rules = acl.GetAccessRules(true, true, typeof(NTAccount));
var currentUser = WindowsIdentity.GetCurrent();
var principal = new WindowsPrincipal(currentUser);
foreach (AuthorizationRule rule in rules)
{
var fsAccessRule = rule as FileSystemAccessRule;
if (fsAccessRule == null)
continue;
if ((fsAccessRule.FileSystemRights & accessRights) > 0)
{
var ntAccount = rule.IdentityReference as NTAccount;
if (ntAccount == null)
continue;
if (principal.IsInRole(ntAccount.Value))
{
if (fsAccessRule.AccessControlType == AccessControlType.Deny)
return false;
isInRoleWithAccess = true;
}
}
}
}
catch (UnauthorizedAccessException)
{
return false;
}
return isInRoleWithAccess;
}
Вы можете попробовать следующий блок кода, чтобы проверить, имеет ли каталог доступ к записи. Он проверяет FileSystemAccessRule.
string directoryPath = "C:\\XYZ"; //folderBrowserDialog.SelectedPath;
bool isWriteAccess = false;
try
{
AuthorizationRuleCollection collection =
Directory.GetAccessControl(directoryPath)
.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount));
foreach (FileSystemAccessRule rule in collection)
{
if (rule.AccessControlType == AccessControlType.Allow)
{
isWriteAccess = true;
break;
}
}
}
catch (UnauthorizedAccessException ex)
{
isWriteAccess = false;
}
catch (Exception ex)
{
isWriteAccess = false;
}
if (!isWriteAccess)
{
//handle notifications
}
У вас есть потенциальное состояние гонки в вашем коде - что произойдет, если у пользователя есть права на запись в папку при проверке, но до того, как пользователь действительно пишет в папку, это разрешение будет снято? Запись создаст исключение, которое вам нужно будет поймать и обработать. Поэтому первоначальная проверка бессмысленна. Вы можете также просто написать и обработать любые исключения. Это стандартный шаблон для вашей ситуации.
http://www.codeproject.com/KB/files/UserFileAccessRights.aspx
Очень полезно Класс, проверьте улучшенную версию в сообщениях ниже.
Просто попытка получить доступ к указанному файлу не обязательно достаточно. Тест будет выполняться с разрешениями пользователя, запускающего программу. Это не обязательно разрешения пользователя, с которыми вы хотите протестировать.
Я не могу заставить GetAccessControl() генерировать исключение в Windows 7, как рекомендовано в принятом ответе.
В итоге я использовал вариант ответа sdds:
try
{
bool writeable = false;
WindowsPrincipal principal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
DirectorySecurity security = Directory.GetAccessControl(pstrPath);
AuthorizationRuleCollection authRules = security.GetAccessRules(true, true, typeof(SecurityIdentifier));
foreach (FileSystemAccessRule accessRule in authRules)
{
if (principal.IsInRole(accessRule.IdentityReference as SecurityIdentifier))
{
if ((FileSystemRights.WriteData & accessRule.FileSystemRights) == FileSystemRights.WriteData)
{
if (accessRule.AccessControlType == AccessControlType.Allow)
{
writeable = true;
}
else if (accessRule.AccessControlType == AccessControlType.Deny)
{
//Deny usually overrides any Allow
return false;
}
}
}
}
return writeable;
}
catch (UnauthorizedAccessException)
{
return false;
}
Надеюсь, что это поможет.
Я согласен с Эшем, это должно быть хорошо. В качестве альтернативы вы можете использовать декларативный CAS и фактически предотвращать запуск программы в первую очередь, если у них нет доступа.
Я считаю, что некоторые функции CAS могут отсутствовать в С# 4.0 из того, что я слышал, не уверен, что это может быть проблемой или нет.
У меня возникла та же проблема: как проверить, могу ли я читать/писать в определенном каталоге. Я закончил с легким решением... на самом деле проверить его. Вот мое простое, но эффективное решение.
class Program
{
/// <summary>
/// Tests if can read files and if any are present
/// </summary>
/// <param name="dirPath"></param>
/// <returns></returns>
private genericResponse check_canRead(string dirPath)
{
try
{
IEnumerable<string> files = Directory.EnumerateFiles(dirPath);
if (files.Count().Equals(0))
return new genericResponse() { status = true, idMsg = genericResponseType.NothingToRead };
return new genericResponse() { status = true, idMsg = genericResponseType.OK };
}
catch (DirectoryNotFoundException ex)
{
return new genericResponse() { status = false, idMsg = genericResponseType.ItemNotFound };
}
catch (UnauthorizedAccessException ex)
{
return new genericResponse() { status = false, idMsg = genericResponseType.CannotRead };
}
}
/// <summary>
/// Tests if can wirte both files or Directory
/// </summary>
/// <param name="dirPath"></param>
/// <returns></returns>
private genericResponse check_canWrite(string dirPath)
{
try
{
string testDir = "__TESTDIR__";
Directory.CreateDirectory(string.Join("/", dirPath, testDir));
Directory.Delete(string.Join("/", dirPath, testDir));
string testFile = "__TESTFILE__.txt";
try
{
TextWriter tw = new StreamWriter(string.Join("/", dirPath, testFile), false);
tw.WriteLine(testFile);
tw.Close();
File.Delete(string.Join("/", dirPath, testFile));
return new genericResponse() { status = true, idMsg = genericResponseType.OK };
}
catch (UnauthorizedAccessException ex)
{
return new genericResponse() { status = false, idMsg = genericResponseType.CannotWriteFile };
}
}
catch (UnauthorizedAccessException ex)
{
return new genericResponse() { status = false, idMsg = genericResponseType.CannotWriteDir };
}
}
}
public class genericResponse
{
public bool status { get; set; }
public genericResponseType idMsg { get; set; }
public string msg { get; set; }
}
public enum genericResponseType
{
NothingToRead = 1,
OK = 0,
CannotRead = -1,
CannotWriteDir = -2,
CannotWriteFile = -3,
ItemNotFound = -4
}
Надеюсь, что это поможет!