在 NUnit 测试中,我需要检查是否可以删除现有文件。UnitUnderTest 源代码如下所示:
public static Boolean IsWritePermissionGranted(String absoluteFilePath)
{
Boolean isGranted = true;
try
{
FileIOPermission writePermission = new FileIOPermission(
FileIOPermissionAccess.Write, absoluteFilePath);
writePermission.Demand();
}
catch (SystemException)
{
isGranted = false;
}
return isGranted;
}
在测试用例中,我想撤销 TestFile 的写权限。到目前为止,我尝试过:
- https://stackoverflow.com/a/7590491/1817029
AddFileSecurity(TEST_FILE_PATH, @"MyDomain\MyUser", FileSystemRights.Write, AccessControlType.Deny);
DirectoryInfo dInfo = new DirectoryInfo(TEST_FILE_PATH);
DirectorySecurity dSecurity = dInfo.GetAccessControl(); dSecurity.AddAccessRule(new FileSystemAccessRule( TEST_FILE_PATH, "MyDomain\MyUser", FileSystemRights.Write, AccessControlType.Deny)); dInfo.SetAccessControl(dSecurity);
在所有情况下,文件仍然可以被删除。我做错了什么?