gpt4 book ai didi

c# - 使用 NLog 的 Windows 服务

转载 作者:行者123 更新时间:2023-11-30 20:13:28 28 4
gpt4 key购买 nike

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

PathToInstalledService\Logs\MyLog.txt

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

谢谢。

最佳答案

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

关于c# - 使用 NLog 的 Windows 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1567513/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com