Search code examples
c#.netwindows-servicesevent-viewer

Windows Service cannot create a text file


Ok so this is my code for the OnStart method

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

I am successfully able to install the service. However when i start i get the message that the service started and then stopped. When i check the Event Viewer it gives me this

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.

Ok what's going on here. I don't think its a permission problem as the ProcessInstaller is set to LocalSystem.


Solution

  • You can use like this

    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");
        }   
     }