Question

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.

Was it helpful?

Solution 2

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

OTHER TIPS

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

I think one line code is more then enough.

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

Appends the specified string to the file, creating the file if it does not already exist.

you should try with the full path for the file, the windows service run in the C:\Windows\System32 folder

string fileName="E:\\Service\\file.txt"
File.Create(file);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top