gpt4 book ai didi

c# - Windows 服务创建文件时拒绝访问路径

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

我无法在我的 Windows 服务中创建文件这是错误

错误在 onstart 方法中访问路径 'C:\Windows\system32\BridgeServiceLog.txt' 被拒绝。

  protected override void OnStart(string[] args)
{


try
{
Logger.InitLogFile("BridgeServiceLog.txt");
Trace.WriteLine(Logger.logSwitch.TraceInfo, "Trace Started");
Trace.WriteLineIf(Logger.logSwitch.TraceInfo, "OnStart Started");

_bridgeServiceEventLog.WriteEntry("new OnStart");
if (Vytru.Platform.Bridge.Configuration.LicenseValidetor.ValidCountAndTypeDevices())
{
SharedData.InitializeBridge();
// WsInitializeBridge();
}
else
{

this.Stop();
_bridgeServiceEventLog.WriteEntry("LicenseValidetor Error");
}
_bridgeServiceEventLog.WriteEntry("end Start");
}
catch (Exception e)
{
Trace.WriteLineIf(Logger.logSwitch.TraceError, e.Message);
_bridgeServiceEventLog.WriteEntry("error In onstart method " + e.Message);
}
Trace.WriteLineIf(Logger.logSwitch.TraceInfo, "OnStart Ended");

}

最佳答案

服务用户帐户可能无权写入 C:\Windows\System32(这是 Windows 服务的工作目录)。

无论如何,您不应该写入该文件夹。它适用于操作系统 - 而不是您的服务。

您可以使用 Environment.GetFolderPath获得一个合适的路径来以一种适用于任何计算机的方式写入日志文件之类的文件,而不仅仅是您自己的计算机。这是一个例子。

var companyPath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),
"MyCompany"
);
var productPath = Path.Combine(companyPath, "MyProduct");
var logFilePath = Path.Combine(productPath, "BridgeServiceLog.txt");

您当然应该为 MyCompanyMyProduct 使用合适的值。

关于c# - Windows 服务创建文件时拒绝访问路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12161749/

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