+92 332 4229 857 99ProjectIdeas@Gmail.com

Lock And Unlock A Folder (C#.net)




The following code shows you how to lock and unlock a folder. User can browse the specific folder to lock/Unlock it.





using System.IO;
using System.Security.AccessControl;

private void btnBrowse_Click(object sender, EventArgs e)
{

   if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
   {
        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);
     } 
}



2 comments:

Azad Chouhan said...

I try this code but when I unlock my folder the icons of the files in folder change to a lock icon.. why this happen? Can u tell me why this happen?

Anonymous said...

In your both button you put AccessControlType.Deny in FileSystemAccessRule. But in unlock button it should be AccessControlType.Allow