简体   繁体   中英

How to limit folder/sub folders/files access to a program only?

I am creating ac# winforms application.

And I have a folder ScanRepository, and I want to prevent other programs and windows users to open this folder, sub folders and files, with a kind of password or a key, and to be able to open them in my c# code.

Any suggestion?

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

The most obvious answer is that most things that let your user in, will let other apps in.. if you lock a folder to a user, while that folder is unlocked to that user other apps can see in too cos the user can see in.

best way is to have a service running as an account that the user cant use. Then, you lock the access to only that account (and system, if you want backups of it), then you make a service that handles any access to those files and lists etc it interfaces with your app.. so in your users eyes they have access, in essense they dont.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM