【问题标题】:Windows Service with NLog带有 NLog 的 Windows 服务
【发布时间】:2009-10-14 16:38:24
【问题描述】:

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

PathToInstalledService\Logs\MyLog.txt

这当然需要管理员权限。所以我的问题是,在为服务创建安装时,我应该在 ServiceProcessInstaller 上使用什么帐户。我目前一直在使用 LocalService,但此帐户没有所需的权限。

谢谢。

【问题讨论】:

    标签: c# windows-services nlog


    【解决方案1】:

    在安装过程中,您应该更改“日志”目录的权限,以允许您的服务帐户写入文件。使用执行服务功能所需权限最少的帐户,通常是 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);
        }
    

    【讨论】:

    • 是否应该在ProjectInstaller类的初始化时调用这段代码?
    • 我会为此创建一个安装工具类并将服务安装程序添加到其中:msdn.microsoft.com/en-us/library/…
    • 知道如何从 Installer 类中获取特定安装文件夹的路径吗?
    • 这可以满足我的需要,我在自定义安装程序的 OnAfterInstall 事件中调用此方法。但是,目前我正在硬编码安装路径,如果您可以更新您的解决方案,我可以如何以编程方式获取安装目录,这将是理想的。
    • 只需使用上面的 AfterInstall 事件。它应该是 Install 类的成员,或者将 'this.Context' 替换为 'installer.Context'。
    猜你喜欢
    • 1970-01-01
    • 2011-05-29
    • 1970-01-01
    • 1970-01-01
    • 2012-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多