我有一个用 C# 编写的控制台程序,它在用户 foo 下运行。该程序创建一个文件。在某些情况下,在 IUSR 下运行的 Web 应用程序需要能够删除控制台应用程序创建的文件。
我想在创建文件时向 IUSR 授予 DELETE (或任何等效的操作)。我怎样才能在 C# 中做到这一点?
我发现了文件IO权限 http://msdn.microsoft.com/en-us/library/system.security.permissions.fileiopermission(VS.80).aspx我不确定那是做什么的,但由于您无法指定特定用户,所以我很确定这就是我现在需要的。
有人对如何做到这一点有好的指导吗?
[顺便说一下,我意识到在某些情况下授予 IUSR 对任何文件的删除权限将是一件相当危险的事情,但在这种情况下,所涉及文件的性质意味着我很乐意将这些权限授予 IUSR]
@Sabau:感谢您对答案的修改 - 它激励我再试一次,这次我似乎已经解决了。我编写了一个小测试程序,以便其他人可以看到它是如何完成的。在我的测试中,我给了 IUSR 完全控制权,但显然你可以添加/拒绝任何你喜欢的内容。
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Security.Permissions;
using System.Security.Principal;
using System.Security.AccessControl;
namespace GrantingFilePermsTests
{
class Program
{
static void Main(string[] args)
{
string strFilePath1 = "E:/1.txt";
string strFilePath2 = "E:/2.txt";
if (File.Exists(strFilePath1))
{
File.Delete(strFilePath1);
}
if (File.Exists(strFilePath2))
{
File.Delete(strFilePath2);
}
File.Create(strFilePath1);
File.Create(strFilePath2);
// Get a FileSecurity object that represents the
// current security settings.
FileSecurity fSecurity = File.GetAccessControl(strFilePath1);
// Add the FileSystemAccessRule to the security settings.
fSecurity.AddAccessRule(new FileSystemAccessRule("IUSR_SOMESERVER",FileSystemRights.FullControl,AccessControlType.Allow));
// Set the new access settings.
File.SetAccessControl(strFilePath1, fSecurity);
}
}
}
感谢大家的回复。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)