Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Lock Folder in C#

Tags:

c#

I want to have lock on my folder permanently using C#.

That lock should be accessed by the application only whenever it is requested. When the application is closed, that lock should not be accessible. Also when the application is running, that folder cannot be moved or opened outside the application. Means, only through my application that folder should be accessed.

like image 271
hadi Avatar asked Nov 16 '10 19:11

hadi


3 Answers

The Following code will help to lock and unlock the folder.

Source: 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);
     } 
}
like image 175
Golda Avatar answered Nov 14 '22 18:11

Golda


In short, C# alone won't get you what you want. A program can lock a resource only while it's running.

What you could do is set up a user who is the owner of that folder, and the only one that can read/write to it. This can be done with Active Directory or plain ol' Windows user accounts. Keep in mind that you will usually want to let Administrators in too, so if something goes wrong you can fix it without having to be this new user (who may not have other needed permissions to fix the problem). Then, have your program authenticate itself as that user (probably by impersonation), and it will be able to use the folder, but others won't.

What will this file contain? If you're looking to store sensitive data, or data that should not be changed, I would put it in a DB. I say this for several reasons; first, it's much easier to connect to a DB as a different user than it is for a program to impersonate a different Windows user than the one running the program. Programmatic administration of folder rights also requires giving your program administrative privileges. DBs also allow very fine granularity over data access (down to the column level). Finally, you're much less likely to end up with a bug and field complaints that your program has created an inaccessible, space-wasting folder on a user's computer that they can't remove even after uninstalling the program.

like image 37
KeithS Avatar answered Nov 14 '22 18:11

KeithS


You can open a file folder by PInvoking CreateFile and setting the FILE_FLAG_BACKUP_SEMANTICS flag.

Have a look at the example below:

// Create a directory named DirToLock
const string directoryName = "DirToLock";
if (!Directory.Exists(directoryName))
{
    Directory.CreateDirectory(directoryName);
}

// Open and lock the directory we've just created
var handle = CreateFile(
    directoryName, 
    FileAccess.Read, 
    FileShare.None, // Causes all requests to open this file to fail until the file is closed.
    IntPtr.Zero, 
    FileMode.Open,
    (FileAttributes) BackupSemantics, // BackupSemantics = 0x02000000
    IntPtr.Zero
);

As for

When the application is closed, that lock should not be accessible

The code above will cause the directory to remain locked as long as the process is running. To unlock the directory while the program is still running, you'll need to close its handle (i.e. by PInvoking CloseHandle):

CloseHandle(handle);
like image 27
fardjad Avatar answered Nov 14 '22 18:11

fardjad