gpt4 book ai didi

c# - 如何在 C# 中锁定文件夹

转载 作者:太空狗 更新时间:2023-10-29 21:41:59 26 4
gpt4 key购买 nike

我想使用 C# 永久锁定我的文件夹。

只有在请求时应用程序才能访问该锁。当应用程序关闭时,不应访问该锁。此外,当应用程序正在运行时,无法在应用程序外部移动或打开该文件夹。意思是,只能通过我的应用程序访问该文件夹。

最佳答案

以下代码将有助于锁定和解锁文件夹。

来源:http://bitsbyta.blogspot.de/2011/01/lock-and-unlock-folder-cnet.html

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

关于c# - 如何在 C# 中锁定文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4198048/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com