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 ?
To change the permission of a file, create (form) the command using the chmod command and pass it into the system() function.
chmod() — Change the mode of a file or directory.
'-' 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).
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With