2009-10-14 64 views
2

我正在创建一个Windows服务,我想使用NLog。我希望将日志写入服务的安装位置,例如:Windows服务与NLog

PathToInstalledService\Logs\MyLog.txt 

这当然需要管理员密码。所以我的问题是,在为服务创建安装时,我应该在ServiceProcessInstaller上使用哪个帐户。我一直在使用LocalService,但该帐户没有所需的高程。

谢谢。

回答

7

在安装期间,您应该更改“日志”目录的权限以允许您的服务帐户写入文件。使用执行服务功能所需的权限最小的帐户,通常是NETWORK SERVICE帐户。

您可以从安装类的服务做到这一点:

void Installer1_AfterInstall(object sender, InstallEventArgs e) 
    { 
     string myAssembly = Path.GetFullPath(this.Context.Parameters["assemblypath"]); 
     string logPath = Path.Combine(Path.GetDirectoryName(myAssembly), "Logs"); 
     Directory.CreateDirectory(logPath); 
     ReplacePermissions(logPath, WellKnownSidType.NetworkServiceSid, FileSystemRights.FullControl); 
    } 

    static void ReplacePermissions(string filepath, WellKnownSidType sidType, FileSystemRights allow) 
    { 
     FileSecurity sec = File.GetAccessControl(filepath); 
     SecurityIdentifier sid = new SecurityIdentifier(sidType, null); 
     sec.PurgeAccessRules(sid); //remove existing 
     sec.AddAccessRule(new FileSystemAccessRule(sid, allow, AccessControlType.Allow)); 
     File.SetAccessControl(filepath, sec); 
    } 
+0

如果这种代码在ProjectInstaller类的初始化叫什么? – James 2009-10-14 17:00:06

+0

我会为此创建一个安装util类并将服务安装程序添加到它:http://msdn.microsoft.com/en-us/library/system.configuration.install.installer.aspx – 2009-10-14 17:48:09

+0

任何想法如何我可以得到安装程序类中的特定安装文件夹的路径? – James 2009-10-14 20:56:56