开发者

Set File Permissions in C#

开发者 https://www.devze.com 2023-04-09 19:21 出处:网络
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开发者_StackOverflow中文版 me ?Is this about attributes (see jb.\'s

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开发者_StackOverflow中文版 me ?


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


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

    private static FileAttributes RemoveAttribute(FileAttributes attributes, FileAttributes attributesToRemove)
    {
        return attributes & ~attributesToRemove;
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消