我正在创建一个我想使用 NLog 的 Windows 服务。我希望将日志写入服务的安装位置,例如:
PathToInstalledService\Logs\MyLog.txt
这当然需要管理员权限。所以我的问题是,在为服务创建安装时,我应该在 ServiceProcessInstaller 上使用什么帐户。我目前一直在使用 LocalService,但此帐户没有所需的提升。
谢谢。
我正在创建一个我想使用 NLog 的 Windows 服务。我希望将日志写入服务的安装位置,例如:
PathToInstalledService\Logs\MyLog.txt
这当然需要管理员权限。所以我的问题是,在为服务创建安装时,我应该在 ServiceProcessInstaller 上使用什么帐户。我目前一直在使用 LocalService,但此帐户没有所需的提升。
谢谢。
在安装过程中,您应该更改“日志”目录的权限,以允许您的服务帐户写入文件。使用具有执行服务功能所需的最低权限的帐户,通常是 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);
}