c# - C# .Net FileSystemRights 拒绝删除权限并稍后添加
问题描述
我的程序生成一个文件。这个文件应该受到保护,这样用户就不会意外删除它。因此,它需要以某种方式加以保护。
由于文件应该受到保护,而应用程序关闭时 FileStream.Lock不是此任务的合适解决方案。
我试图在文件上拒绝 FileSystemRights.Delete,例如:
fSecurity.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null),
FileSystemRights.Delete, AccessControlType.Deny));
但这并不能阻止删除,为此我必须像这样更改它:
fSecurity.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null),
FileSystemRights.Delete | FileSystemRights.WriteAttributes, AccessControlType.Deny));
(用户可以打开文件属性并添加回 WriteAttribute 权限,然后可以删除文件,这很好)
现在的问题是:该文件应该可以从应用程序中删除。但是做:
fSecurity.RemoveAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null),
FileSystemRights.Delete | FileSystemRights.WriteAttributes, AccessControlType.Deny));
// or:
fSecurity.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null),
FileSystemRights.Delete | FileSystemRights.WriteAttributes, AccessControlType.Allow));
导致 UnauthorizedAccessException。所以我不能撤销我所做的。这很奇怪,因为在文件资源管理器中它绝对有可能这样做。
所以我的问题是 -您如何再次授予删除权限-或者:保护文件以防意外删除的最佳方法是什么
该文件已在 %appdata% 中,但由于用户可能会删除其他文件夹,因此绝对不能意外删除此文件
解决方案
@canton7 谢谢!这非常有帮助
好的,经过反复试验,我得到了解决方案:
- 您必须将文件设置为只读。单独拒绝删除不起作用
您必须拒绝删除 + WriteAttributes - 如果您不这样做,可以在文件资源管理器中删除文件而无需请求权限。
再次解锁文件时:先加回权限
- 你必须删除你添加的拒绝规则
- 并且您必须添加标志以允许
- 只做其中一项是行不通的
- 删除只读标志
private static void LockFile(string _FullPath)
{
File.SetAttributes(_FullPath, File.GetAttributes(_FullPath) | FileAttributes.ReadOnly);
FileSecurity fSecurity = File.GetAccessControl(_FullPath);
fSecurity.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null),
FileSystemRights.Delete | FileSystemRights.WriteAttributes, AccessControlType.Deny));
File.SetAccessControl(_FullPath, fSecurity);
}
private static void UnLockFile(string _FullPath)
{
FileSecurity fSecurity = File.GetAccessControl(_FullPath);
fSecurity.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null),
FileSystemRights.Delete | FileSystemRights.WriteAttributes, AccessControlType.Allow));
fSecurity.RemoveAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null),
FileSystemRights.Delete | FileSystemRights.WriteAttributes, AccessControlType.Deny));
File.SetAccessControl(_FullPath, fSecurity);
File.SetAttributes(_FullPath, FileAttributes.Normal);
}
推荐阅读
- python - Pytorch 嵌入“自身的索引超出范围”
- reactjs - 如何在 Tailwind 和 postcss 中将 Html 内容转换为纯文本
- react-native - 在来电时触发 RNCallKeep.displayIncomingCall() 的最佳方法是什么?
- kubernetes - NodeSelector 不适用于多个节点池?
- c# - 出现滚动条时如何正确应用修改后的 C# WinForm ListBox 边框颜色
- vb.net - 如何进行格式检查?所以输入格式正确。例如 dd/mm/yy。(Visual Basic)
- pandas - 分位数 groupby 熊猫数据框
- javascript - ReactJS中基于创建日期的对象数组的有序显示
- r - Shiny Timevis - 改变行名的位置
- powershell - Powershell中的高级CSV过滤?