Windows Service cannot create a text file

15,863

Solution 1

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

Solution 2

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

Solution 3

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.

Share:
15,863
Win Coder
Author by

Win Coder

Updated on June 06, 2022

Comments

  • Win Coder
    Win Coder almost 2 years

    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.