【问题标题】:Windows Service cannot create a text fileWindows 服务无法创建文本文件
【发布时间】:2012-12-24 14:21:04
【问题描述】:

好的,这是我的 OnStart 方法代码

File.CreateText("test.txt");
StreamWriter write = File.AppendText("test.txt");
write.WriteLine("Hello world, the service has started");
write.Flush();
write.Close();

我能够成功安装该服务。但是,当我启动时,我收到服务启动然后停止的消息。当我检查事件查看器时,它给了我这个

Service cannot be started. System.IO.IOException: The process cannot access the file 'C:\Windows\system32\test.txt' because it is being used by another process.

好的,这里发生了什么。我不认为这是权限问题,因为 ProcessInstaller 设置为 LocalSystem。

【问题讨论】:

  • 为了测试,请尝试将文件写入c:\test.txt,或任何其他非系统无保护目录。
  • 好吧,我确实试过写 F:\test.txt 得到了同样的错误

标签: c# .net windows-services event-viewer


【解决方案1】:

您应该尝试使用文件的完整路径,Windows 服务在 C:\Windows\System32 文件夹中运行

string fileName="E:\\Service\\file.txt"
File.Create(file);

【讨论】:

    【解决方案2】:

    我认为一行代码就足够了。

      File.AppendAllText(@"path\test.txt", "Hello world, the service has started");
    

    将指定的字符串附加到文件中,如果文件不存在则创建该文件。

    【讨论】:

      【解决方案3】:

      你可以这样使用

      string path = @"path\test.txt";
      if (!File.Exists(path)) 
      {
        // Create a file to write to. 
         using (StreamWriter sw = File.CreateText(path)) 
         {
           sw.WriteLine("Hello world, the service has started");
          }   
       }
      

      【讨论】:

      • 我已经很久没有处理文件了,因此我忘记了转义序列的作用。您为我提供了一个 sn-p 代码,否则对我来说将是一场漫长的斗争。
      【解决方案4】:

      您不需要使用第一个File.CreateText 语句。这会在未关闭的文件上创建一个流编写器。

      您的 File.AppendText 尝试在同一个文件上创建一个新的 StreamWriter,因此您会收到 File in use 错误。

      另外,正如 MSDN 所说,如果您的文件不存在,则会创建它。

      如果路径指定的文件不存在,则创建该文件。如果文件确实存在,则对 StreamWriter 的写入操作将文本附加到文件中

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-07-16
        • 2015-05-03
        • 1970-01-01
        • 2011-04-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多