开发者

Windows Service with NLog

I am creating a Windows Service which I want to use NLog with. I want the logs to be written to the install location of the service say something like:

PathToInstalledService\Logs\MyLog.txt

This is of course going to require administrator priveledges. So my question is, when creating the install for the Service, what account shou开发者_运维技巧ld I use on the ServiceProcessInstaller. I have been currently using LocalService, but this account does not have the required elevation.

Thanks.


During installation you should change the permissions of the 'Logs' directory to allow your service account to write files. Use the account with the least privileges needed to perform your services function, generally the NETWORK SERVICE account.

You can do this from an install class on the 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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜