在C#中设置文件权限

12

我想在C#中将文件的权限设置为“不能删除”,只允许读取。但是我不知道如何实现。你能帮助我吗?

4个回答

15

这是关于属性(参见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);

请参考如何为我的应用程序创建的文件授予所有用户完全权限?以获得更具体的示例。

根据原始问题,似乎您想禁止FileSystemRights.Delete权限。


代码也在此 MSDN 中。 - yu yang Jian
1
上面的链接(File.AccessControl)是德语版本。对于那些回答“Nein”的人,英文版本在https://learn.microsoft.com/en-us/dotnet/api/system.io.file.setaccesscontrol?view=netframework-4.8。 - Mark Ainsworth

7
请看一下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);
        }

3
我认为问题涉及到“权限”而不是“属性”... - Yousha Aleayoub

2
您忘记复制RemoveAttribute方法,该方法为:
    private static FileAttributes RemoveAttribute(FileAttributes attributes, FileAttributes attributesToRemove)
    {
        return attributes & ~attributesToRemove;
    }

0

这里有一个在.NET Core上应该可以工作的示例:

FileSystemAccessRule rule = new (account, FileSystemRights.FullControl, AccessControlType.Allow);
new FileInfo(filePath).GetAccessControl().AddAccessRule(rule);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接