Search code examples
c#file-permissions

Set File Permissions in C#


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 ?


Solution

  • 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);
            }