在C#中设置文件权限

Yas*_*zel 7 c# file-permissions

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

Ech*_*tor 10

这是关于属性(请参阅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);
Run Code Online (Sandbox Code Playgroud)

请参阅如何授予我的应用程序为所有用户创建的文件的完全权限?举一个更具体的例子。

在原始问题中,听起来好像您要禁止使用该FileSystemRights.Delete权利。


jb.*_*jb. 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);
        }
Run Code Online (Sandbox Code Playgroud)

  • 我认为问题是关于“权限”而不是“属性”...... (3认同)