在C#中设置文件权限

时间:2011-09-28 22:32:01

标签: c# file-permissions

我想在C#中将文件的权限设置为“无法删除”,只能读取。但我不知道该怎么做。你能救我吗?

3 个答案:

答案 0 :(得分:8)

看看File.SetAttributes()。网上有很多关于如何使用它的例子。

取自该MSDN页面:

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

答案 1 :(得分:4)

这是关于属性(参见jb。的回答)还是权限,即读/写访问等?在后一种情况下,请参阅File.SetAccessControl

来自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);

有关更具体的示例,请参阅How to grant full permission to a file created by my application for ALL users?

在原始问题中,您似乎想要禁止FileSystemRights.Delete权利。

答案 2 :(得分:2)

您忘记复制RemoveAttribute方法,即:

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