2012-08-28 30 views
3

我不能在我的窗口服务 创建文件,这是错误对路径的访问被拒绝当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"); 

     } 

回答

5

服务用户帐户可能没有访问写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

5

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

有两种方法可以解决这个问题。将您的文件写入另一个您有权访问的文件夹,或者以管理员权限运行您的服务。

我会推荐第一个选项。

+0

我如何使用管理员权限运行我的服务。 – tito11

+0

进入'services.msc'(Windows键+ R),然后找到您的服务,右键单击转到登录选项卡并配置管理员帐户。 –

0

最简单的解决方案是去你想要保存文件的文件夹,右键单击,属性,安全性,添加一个新用户IIS_Users并给予写入权限。