我想使用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);
}
}
Run Code Online (Sandbox Code Playgroud)
您可以加密您的文件,并在应用程序打开时锁定它们,但您无法阻止其他人删除文件或恢复到文件的先前版本。您可以尝试保留哪个文件签名是最新的记录,但他们也可以恢复该签名。
您应该指定您的用例。
| 归档时间: |
|
| 查看次数: |
13382 次 |
| 最近记录: |