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

标签 c#

我想使用 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/

相关文章:

c# - 验证 TextBox 中的文本更改

c# - Visual Studio 不会构建为 exe (.NET Core 2.0)

c# - 如何使用 C#.net 替换 ListView 中一行中列的值?

c# - 指定 MSTest 宿主区域性

c# - 实现 IDispatch::Invoke 以供 WebBrowser 控件调用

c# - 流利的 NHibernate : how to map the where clause filter on a ManyToMany

c# - 如何检查一个对象是否被定义?

c# - 连接到机器的 USB 设备的路径?

c# - 将 VirtualPathProvider 用于简单的静态文件

c# - 使用授权中间件而不是授权属性 ASP NET Core