【问题标题】:Set File Permissions in C#在 C# 中设置文件权限
【发布时间】:2011-11-27 06:34:42
【问题描述】:

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

【问题讨论】:

    标签: c# file-permissions


    【解决方案1】:

    这是关于属性(参见 jb.'s answer)或权限,即读/写访问权限等吗?在后一种情况下,请参阅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】:

    看看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】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-03
      • 1970-01-01
      • 2011-09-10
      • 2015-10-18
      • 2010-10-10
      相关资源
      最近更新 更多