且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

限制用户不要删除任何文件夹

更新时间:2023-12-01 23:46:16

包含打开文件的任何文件夹都无法删除:因此,在文件夹中创建一个临时文件,将其打开以进行写入,完成后将其关闭并删除.这不会(也不能)防止删除文件夹中的其他文件.

除此之外,我无法阻止从任何来源删除文件夹.
Any folder which contains an open file cannot be deleted: So create a temporary file in the folder, open it for writing, and close and delete it when you are finished. This will not (and cannot) prevent deletion of the other files in the folder.

Other than that, I know of no way to prevent folder deletion from any source.


我解决了这个问题.请告诉我是否还有另一种有效的方法?

首先使用此方法选择当前登录的用户"并保存在字符串变量中:
字符串SysLogUser = System.Security.Principal.WindowsIdentity.GetCurrent().Name;

然后此功能用于冻结用户以进行删除:
(传递文件夹"传递并放弃当前用户)

I solved this. kindly let me know if there is another efficient way to do this ?

First pick Current User Logged In by using this and save in string variable :
string SysLogUser = System.Security.Principal.WindowsIdentity.GetCurrent().Name;

Then this function is for freezing the user for deletion :
(Pass Folder pass and ablove current user)

public void FreezeFolder(string path,string user) 
   {
         System.IO.DirectoryInfo folderInfo = new System.IO.DirectoryInfo(path);
            DirectorySecurity folderSecurity = folderInfo.GetAccessControl();

            FileSystemAccessRule rule =
                new FileSystemAccessRule(
                 user,
                 FileSystemRights.Delete |
                 FileSystemRights.DeleteSubdirectoriesAndFiles,
                 InheritanceFlags.ObjectInherit,
                 PropagationFlags.None,
                 AccessControlType.Deny);
            folderSecurity.AddAccessRule(rule);
            Directory.SetAccessControl(path, folderSecurity);
   }



然后,当您想取消冻结此重构时
(传递文件夹"传递并放弃当前用户)



Then when you want Unfreeze this restruction
(Pass Folder pass and ablove current user)

public void UnfreezeFolder(string path, string user)
   {
      System.IO.DirectoryInfo folderInfo = new System.IO.DirectoryInfo(path);
            DirectorySecurity folderSecurity = folderInfo.GetAccessControl();
            FileSystemAccessRule rule =
                new FileSystemAccessRule(
                 user,
                 FileSystemRights.Delete |
                 FileSystemRights.DeleteSubdirectoriesAndFiles,
                 InheritanceFlags.ObjectInherit,
                 PropagationFlags.None,
                 AccessControlType.Deny);
            folderSecurity.RemoveAccessRule(rule);
            Directory.SetAccessControl(path, folderSecurity);
   }