Я пытаюсь читать полные каталоги независимо от текущих разрешений на файлы. Но даже несмотря на то, что у меня есть «SeBackupPrivilege», следующий код приводит к «UnauthorizedAccessException». Как это может быть?
//Create the test-directory.
string testPath = Path.Combine(Environment.CurrentDirectory, "TestDenied");
string filePath = Path.Combine(testPath, "Foo.txt");
Directory.CreateDirectory(testPath);
using (var fs = File.CreateText(filePath)) {
fs.WriteLine("Foo");
}
var ds = Directory.GetAccessControl(testPath, Utils.AccessControlSectionsToRead);
ds.SetOwner(WindowsIdentity.GetCurrent().User);
ds.AddAccessRule((FileSystemAccessRule)ds.AccessRuleFactory(
WindowsIdentity.GetCurrent().User,
(int)FileSystemRights.FullControl,
false,
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
PropagationFlags.None,
AccessControlType.Deny)
);
Directory.SetAccessControl(testPath, ds);
//Get the backup-privilege
WinAPI.ModifyPrivilege(PrivilegeName.SeBackupPrivilege, true);
//Checked the privilege on the command line here: The process has it.
//Try to access the forbidden file.
using (var fs = File.OpenRead(filePath)) {
//UnauthorizedAccessException from the line above.
}
Как такое могло случиться? Я думал, что SeBackupPrivilege дает мне доступ ко всем файлам?
Гарри имеет в виду то, что CreateFile называется FILE_FLAG_BACKUP_SEMANTICS
. При последней проверке ни один из классов .Net не выставляет этот флаг (вероятно, потому, что он используется так редко).
Однако для тех, кто в этом нуждается, всегда есть PInvoke.