我的程序生成一个文件。这个文件应该受到保护,这样用户就不会意外删除它。因此,它需要以某种方式加以保护。
由于文件应该受到保护,而应用程序关闭时 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% 中,但由于用户可能会删除其他文件夹,因此绝对不能意外删除此文件