繁体   English   中英

在 C# 中设置文件权限

[英]Set File Permissions in C#

我想在 C# 中将文件的权限设置为“无法删除”,只能读取。 但我不知道如何做到这一点。 你能帮助我吗 ?

这是关于属性(参见 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权限。

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

你忘了在 RemoveAttribute 方法中复制,也就是:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM