Windows服务无法创建文本文件

Win*_*der 3 .net c# windows-services event-viewer

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

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

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

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.

rya*_*lli 7

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

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

此外,正如MSDN所说,如果文件不存在,您的文件将被创建.

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


and*_*ndy 5

你可以像这样使用

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");
    }   
 }
Run Code Online (Sandbox Code Playgroud)