Within a NUnit test I need to check whether an existing file can be deleted or not. The UnitUnderTest source looks like:
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;
}
Within the test case I want to revoke the write permission from the TestFile. So far I tried:
- 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);
In all cases the file can still be deleted. What I'm doing wrong?