在 .NET 中保留文件权限
我有一个经常被删除和重新创建的文件(我无法控制这种行为)。但是,重新创建文件时,它不会保留删除之前所拥有的权限。所以我编写了这段代码来尝试解决该问题:
var access = File.GetAccessControl(filepath, AccessControlSections.Access);
deleteAndRecreate(filepath);
File.SetAccessControl(filepath, access);
但这不起作用。如果我明确授予“TestUser”该文件的读取权限,那么在运行此代码后,TestUser 将不再具有读取权限。我做错了什么?
I have a file that is often deleted and recreated (I have no control over this behavior). However when the file is recreated, it doesn't retain the permissions that it had before it was deleted. So I wrote this code to try to fix that problem:
var access = File.GetAccessControl(filepath, AccessControlSections.Access);
deleteAndRecreate(filepath);
File.SetAccessControl(filepath, access);
But this doesn't work. If I explicitly give "TestUser" read permission for the file, then after I run this code, TestUser will no longer have read permissions. What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不加第二个参数试试
Try it without the second parameter
我的猜测是,一旦文件被删除,
GetAccessControl
返回的FileSecurity
对象就不再有效。您是否尝试过类似的方法(未经测试)?
(如果这种通用方法有效,您也许能够从之前创建的
access
对象中获取访问规则并重用它们。它们很可能在删除后保持有效。)My guess would be that the
FileSecurity
object returned byGetAccessControl
is no longer valid once the file is deleted.Have you tried something like this instead (untested)?
(If this general approach works, you might be able to get the access rules out of the
access
object you were creating before and reuse those. They might well stay valid through the delete.)删除文件,重新创建它,然后使用以下命令恢复原始权限:
Delete the file, recreate it and then restore the original permissions using: