如何在C#中锁定文件夹
当前位置:点晴教程→知识管理交流
→『 技术文档交流 』
以下代码可以用来锁定和解锁文件夹,基本原理是在锁定时将目录的访问权限改为指定人员才有权限访问,解锁时将权限设置为所有用户都可以访问。 using System.IO; using System.Security.AccessControl;
private void btnBrowse_Click(object sender, EventArgs e) { if (folderBrowserDialog1.ShowDialog() == DialogResult.OK) { // Select the folder to lock textBox1.Text = folderBrowserDialog1.SelectedPath; } }
private void btnLock_Click(object sender, EventArgs e) { try { string folderPath = textBox1.Text; string adminUserName = Environment.UserName;// getting your adminUserName DirectorySecurity ds = Directory.GetAccessControl(folderPath); FileSystemAccessRule fsa = new FileSystemAccessRule(adminUserName, FileSystemRights.FullControl, AccessControlType.Deny) ds.AddAccessRule(fsa); Directory.SetAccessControl(folderPath, ds); MessageBox.Show("Locked"); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
private void btnUnLock_Click(object sender, EventArgs e) { try { string folderPath = textBox1.Text; string adminUserName = Environment.UserName;// getting your adminUserName DirectorySecurity ds = Directory.GetAccessControl(folderPath); FileSystemAccessRule fsa = new FileSystemAccessRule(adminUserName,FileSystemRights.FullControl, AccessControlType.Deny) ds.RemoveAccessRule(fsa); Directory.SetAccessControl(folderPath, ds); MessageBox.Show("UnLocked"); } catch (Exception ex) { MessageBox.Show(ex.Message); } } 该文章在 2024/1/9 2:19:49 编辑过 |
关键字查询
相关文章
正在查询... |