Windows Service cannot create a text file

Win Coder picture Win Coder · Jan 10, 2013 · Viewed 15.3k times · Source

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.

Answer

Ravi Y picture Ravi Y · Jan 10, 2013

You do not need to use the first File.CreateText statement. This creates a stream writer on the file which is not closed.

Your File.AppendText tries to create a new StreamWriter on the same file and hence you get the File in use error.

Also, as MSDN says your file will be created if it does not exist.

If the file specified by path does not exist, it is created. If the file does exist, write operations to the StreamWriter append text to the file