Setting security on a single file?

2020-07-17 04:41发布

I am trying to implement a security on a single file to prevent either accessing the file or deleting it here is the code :

//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();

I have tried to open the file again after closing the stream and setting the access control but same problem occurred, i have tried also it on a normal file other than a file stream and the same too, I have an admin account with all permissions so What is the problem and how to Solver it ?

标签: c# security file
1条回答
放我归山
2楼-- · 2020-07-17 05:36

try this,

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);
查看更多
登录 后发表回答