繁体   English   中英

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

[英]Access to the path is Denied When create file by windows service

我无法在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使用合适的值。

运行Windows服务时,默认工作文件夹为<System drive>:\\Windows\\System32\\
幸运的是,并非所有人都可以访问该文件夹。

有两种解决方法: 将文件写入您拥有权限的另一个文件夹,或使用管理员权限运行服务。

我建议第一个选择。

最简单的解决方案是转到要保存文件的文件夹,右键单击,属性,安全性,添加新用户IIS_Users并授予写权限。

在ProjectInstaller上使用LocalSystem帐户

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM