我正在使用Web安装项目来安装我的ASP.NET应用程序,该应用程序需要写入主虚拟目录文件夹下的文件夹。如何配置安装项目以授予ASPNET用户对该文件夹的权限?
答案 0 :(得分:6)
这样做的方法是创建一个派生自System.Configuration.Install.Installer
的类。覆盖Install()
方法。以下是更改目录和文件权限的示例,您可能不希望如此宽容,但这取决于您的安全上下文。为了使其工作,安装项目必须将其作为自定义操作运行。从该类所在的任何项目中添加“主要输出”。您还需要将该目录传递给其属性中的自定义操作。第一个变量名必须与代码匹配。像这样:/targetdir="[TARGETDIR]\"
[RunInstaller(true)]
public partial class SetPermissions : Installer
{
private const string STR_targetdir = "targetdir";
private const string STR_aspnetUser = "ASPNET";
public SetPermissions()
{
InitializeComponent();
}
public override void Install(IDictionary stateSaver)
{
base.Install(stateSaver);
Context.LogMessage(
Context.Parameters
.Cast<DictionaryEntry>()
.Select(entry => String.Format("String = {0} Value = {1}", entry.Key, entry.Value))
.Aggregate(new StringBuilder("From install\n"), (accumulator, next) => accumulator.AppendLine(next))
.ToString()
);
string targetDir = Context.Parameters[STR_targetdir];
string dbDir = Path.Combine(targetDir, "db");
AddFullControlPermissionToDir(dbDir, STR_aspnetUser);
string rimdbSqliteFilename = Path.Combine(dbDir, "db.sqlite");
AddFullControlPermissionToFile(rimdbSqliteFilename, STR_aspnetUser);
string logsDir = Path.Combine(targetDir, "logs");
AddFullControlPermissionToDir(logsDir, STR_aspnetUser);
}
private static void AddFullControlPermissionToDir(string dir, string user)
{
DirectorySecurity directorySecurity = Directory.GetAccessControl(dir);
directorySecurity.AddAccessRule(
new FileSystemAccessRule(
user,
FileSystemRights.FullControl,
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
PropagationFlags.None,
AccessControlType.Allow));
Directory.SetAccessControl(dir, directorySecurity);
}
private static void AddFullControlPermissionToFile(string filename, string user)
{
FileSecurity fileSecurity = File.GetAccessControl(filename);
fileSecurity.AddAccessRule(
new FileSystemAccessRule(
user,
FileSystemRights.FullControl,
AccessControlType.Allow));
File.SetAccessControl(filename, fileSecurity);
}
}