12

I wanna set the permissions on a file to "can not be deleted" in C#, only readable. But I don't know how to do this. Can you help me ?

Taryn East
  • 27,486
  • 9
  • 86
  • 108
Yasin Ozel
  • 273
  • 1
  • 6
  • 15

4 Answers4

15

Is this about attributes (see jb.'s answer) or permissions, i.e. read/write access, etc.? In the latter case see File.SetAccessControl.

From the MSDN:

// Get a FileSecurity object that represents the
// current security settings.
FileSecurity fSecurity = File.GetAccessControl(fileName);

// Add the FileSystemAccessRule to the security settings.
fSecurity.AddAccessRule(new FileSystemAccessRule(account, rights, controlType));

// Set the new access settings.
File.SetAccessControl(fileName, fSecurity);

See How to grant full permission to a file created by my application for ALL users? for a more concrete example.

In the original question it sounds like you want to disallow the FileSystemRights.Delete right.

Echsecutor
  • 775
  • 8
  • 11
  • the code is also in this [MSDN](https://learn.microsoft.com/zh-tw/dotnet/api/system.security.accesscontrol.filesystemaccessrule?view=netframework-4.8) – yu yang Jian Aug 11 '19 at 12:13
  • 1
    The link above (File.AccessControl) is the German language version. The English version is at https://learn.microsoft.com/en-us/dotnet/api/system.io.file.setaccesscontrol?view=netframework-4.8 for those who answer 'Nein.' to Sprichst du Deutsch' – Mark Ainsworth Sep 24 '19 at 16:10
7

Take a look at File.SetAttributes(). There are lots of examples online about how to use it.

Taken from that MSDN page:

FileAttributes attributes = File.GetAttributes(path);

        if ((attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
        {
            // Show the file.
            attributes = RemoveAttribute(attributes, FileAttributes.Hidden);
            File.SetAttributes(path, attributes);
            Console.WriteLine("The {0} file is no longer hidden.", path);
        } 
        else 
        {
            // Hide the file.
            File.SetAttributes(path, File.GetAttributes(path) | FileAttributes.Hidden);
            Console.WriteLine("The {0} file is now hidden.", path);
        }
jb.
  • 9,921
  • 12
  • 54
  • 90
2

You forgot to copy in the RemoveAttribute method, which is:

    private static FileAttributes RemoveAttribute(FileAttributes attributes, FileAttributes attributesToRemove)
    {
        return attributes & ~attributesToRemove;
    }
MelloG
  • 1,044
  • 1
  • 11
  • 11
0

Here is an example that should work on .NET Core:

FileSystemAccessRule rule = new (account, FileSystemRights.FullControl, AccessControlType.Allow);
new FileInfo(filePath).GetAccessControl().AddAccessRule(rule);
Rune Aamodt
  • 2,551
  • 2
  • 23
  • 27