Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 609
Yasin Ozel Avatar asked Sep 28 '11 22:09

Yasin Ozel


People also ask

How do I change permissions in C?

To change the permission of a file, create (form) the command using the chmod command and pass it into the system() function.

What does chmod do in C?

chmod() — Change the mode of a file or directory.

What is C in file permissions?

'-' means a regular file, 'd' would mean a directory, 'l' would mean a link. There are also other types such as 'c' for character device and 'b' for block device (found in the /dev/ directory). These are the permissions for the owner of the file (the user who created the file).


2 Answers

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.

like image 150
Echsecutor Avatar answered Oct 11 '22 02:10

Echsecutor


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);
        }
like image 45
jb. Avatar answered Oct 11 '22 01:10

jb.