在 .NET 中保留文件权限

发布于 2024-12-18 21:04:41 字数 332 浏览 2 评论 0原文

我有一个经常被删除和重新创建的文件(我无法控制这种行为)。但是,重新创建文件时,它不会保留删除之前所拥有的权限。所以我编写了这段代码来尝试解决该问题:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

我偏爱纯白色 2024-12-25 21:04:41

不加第二个参数试试

var access = File.GetAccessControl(filepath); 
deleteAndRecreate(filepath); 
File.SetAccessControl(filepath, access); 

Try it without the second parameter

var access = File.GetAccessControl(filepath); 
deleteAndRecreate(filepath); 
File.SetAccessControl(filepath, access); 
草莓酥 2024-12-25 21:04:41

我的猜测是,一旦文件被删除,GetAccessControl 返回的 FileSecurity 对象就不再有效。

您是否尝试过类似的方法(未经测试)?

deleteAndRecreate(filepath);
FileSecurity access = File.GetAccessControl(filepath, AccessControlSections.Access);
access.AddAccessRule(new FileSystemAccessRule(account, rights, controlType));

(如果这种通用方法有效,您也许能够从之前创建的 access 对象中获取访问规则并重用它们。它们很可能在删除后保持有效。)

My guess would be that the FileSecurity object returned by GetAccessControl is no longer valid once the file is deleted.

Have you tried something like this instead (untested)?

deleteAndRecreate(filepath);
FileSecurity access = File.GetAccessControl(filepath, AccessControlSections.Access);
access.AddAccessRule(new FileSystemAccessRule(account, rights, controlType));

(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.)

独留℉清风醉 2024-12-25 21:04:41
//Get current attributes
var fileAttributes = File.GetAttributes(filePath);

删除文件,重新创建它,然后使用以下命令恢复原始权限:

//Restore the file's original attributes
File.SetAttributes(filePath, fileAttributes);
//Get current attributes
var fileAttributes = File.GetAttributes(filePath);

Delete the file, recreate it and then restore the original permissions using:

//Restore the file's original attributes
File.SetAttributes(filePath, fileAttributes);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文