简体   繁体   中英

How do I revoke write permission from a file so that it can't be deleted in C#

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:

  1. https://stackoverflow.com/a/7590491/1817029
  2. AddFileSecurity(TEST_FILE_PATH, @"MyDomain\\MyUser", FileSystemRights.Write, AccessControlType.Deny);
  3. 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?

The simplest and quickest way of preventing accidental deletion is just to make it read-only:

File.SetAttributes(path, FileAttributes.ReadOnly);

Any code that wishes to modify or delete this file will have to explicitly remove the read-only attribute first (ie with another call to SetAttributes ).

You should also never catch SystemException (or Exception for that matter), and anyway your example code is dealing with CAS which has nothing to do with file security.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM