c# - 在单个文件上设置安全性?

标签 c# security file

我正在尝试在单个文件上实现安全措施以防止访问文件或删除文件,代码如下:

//Create file
FileStream oFileStreamDec = new FileStream(@"C:\Decrypted_AMS.cfg", FileMode.Create, FileAccess.ReadWrite, FileShare.None);
oFileStreamDec.Write(DecryptedXML, 0, DecryptedXML.Length);
//Create access rules
FileSystemAccessRule oAccessRuleFullControl = new FileSystemAccessRule(WindowsIdentity.GetCurrent().Name, FileSystemRights.FullControl, AccessControlType.Allow);
//Create file security and apply rules to it
FileSecurity oFileSecurity = new FileSecurity(@"C:\Decrypted_AMS.cfg", AccessControlSections.All);
oFileSecurity.AddAccessRule(oAccessRuleFullControl);
//Here is the problem !!!!!!!
oFileStreamDec.SetAccessControl(oFileSecurity);
oFileStreamDec.Close();

我试图在关闭流并设置访问控制后再次打开文件,但发生了同样的问题,我也在文件流以外的普通文件上尝试过,同样的,我有一个管理员帐户所有权限所以问题是什么以及如何解决?

最佳答案

试试这个,

FileStream oFileStreamDec = new FileStream(@"C:\Decrypted_AMS.cfg", FileMode.Create, FileAccess.ReadWrite, FileShare.None);
oFileStreamDec.Write(DecryptedXML, 0, DecryptedXML.Length);
// Close the File first
oFileStreamDec.Close();
//Create file security and apply rules to it
FileSecurity oFileSecurity = new FileSecurity();
oFileSecurity.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule("Everyone", System.Security.AccessControl.FileSystemRights.FullControl, System.Security.AccessControl.AccessControlType.Allow));
System.IO.File.SetAccessControl(@"C:\Decrypted_AMS.cfg", oFileSecurity);

关于c# - 在单个文件上设置安全性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7804800/

相关文章:

python - 关闭文件 python

java - 将文件读入数组返回错误的元素

c# - ASP.NET MVC5 Controller 操作只能使用 RedirectToAction 访问

php - 什么时候最推荐使用 mysql_real_escape_string()

c# - 获取 WPF ComboBox 中所选项目的标签

asp.net-mvc - asp.net mvc 中的安全问题是什么?

security - 使用 x509 证书的安全连接

java - VFS FileObject无法删除文件

c# - 如何从 gridview 中的 TimeSelector 检索时间?

用户输入后的 C# 时间延迟