1

我创建了一个应用程序,它将拒绝对文件夹的所有完全控制访问,直到有人使用正确的密码登录应用程序。我的锁定程序的来源是:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Security.AccessControl;
using System.DirectoryServices;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string Directoryd = "D:";
            string mydirectory = Directoryd + "\\" + "rs\\";
            if (!Directory.Exists(mydirectory))
            {
                Directory.CreateDirectory(mydirectory);
            }
            DirectoryInfo di = new DirectoryInfo(mydirectory);
            DirectorySecurity ds = di.GetAccessControl();


            ds.AddAccessRule(new FileSystemAccessRule(
                @"everyone",
                FileSystemRights.FullControl,
                AccessControlType.Deny));

            di.SetAccessControl(ds);
        }      
    }
}

这将拒绝对文件夹 D:/rs/ 的所有访问我想到了一个脚本,它可以在按下按钮时解锁文件夹,如下所示:

private void login_Click(object sender, EventArgs e)
{
    string username = text1.Text;
    string password = text2.Text;
    if(username == "aname" && password == "password")
    {
        string Directoryd = "D:";
        string mydirectory = Directoryd + "\\" + "rs\\";
        if (!Directory.Exists(mydirectory))
        {
            Directory.CreateDirectory(mydirectory);
        }
        DirectoryInfo di = new DirectoryInfo(mydirectory);
        DirectorySecurity ds = di.GetAccessControl();


        ds.AddAccessRule(new FileSystemAccessRule(
            @"everyone",
            FileSystemRights.FullControl, 
            AccessControlType.Allow));

        di.SetAccessControl(ds);
    }
}

但这显示访问被拒绝错误。如何避免这个错误?

4

2 回答 2

2

拒绝许可的优先级高于允许。您必须删除拒绝权限而不添加另一个权限。

于 2012-07-14T05:24:00.177 回答
0

尝试替换这个:

ds.AddAccessRule(new FileSystemAccessRule(@"everyone", FileSystemRights.FullControl, AccessControlType.Allow));
di.SetAccessControl(ds);

ds.AddAccessRule(new FileSystemAccessRule(@"everyone", FileSystemRights.FullControl, AccessControlType.Deny));
di.RemoveAccessRule(ds);

希望这会有所帮助。

于 2015-09-23T14:04:34.363 回答