Search code examples
c#filestreamwriter

C# StreamWriter not closing the file after appending


So im using a timer which appends logs to a log file every minute. For some reason I get the error that the file is in use even tho it shouldn't. It works twice and then the third time I an error.

using (StreamWriter sw = File.AppendText("logs.txt"))
{
     sw.WriteLine("My logs");
}

This is the timer that executes the code above

System.Timers.Timer timer = new System.Timers.Timer(TimeSpan.FromMinutes(1).TotalMilliseconds);
timer.Elapsed += (s,e) => { WriteToLog(); };
timer.AutoReset = true;

timer.Start();

The error: The process cannot access the file because it is being used by another process.


Solution

  • Here is a basic example of what you are kind of wanting to do.

    void Main()
    {
            System.Timers.Timer timer = new System.Timers.Timer(TimeSpan.FromMinutes(1).TotalMilliseconds);
            timer.Elapsed += WriteToLog;
            timer.Enabled = true;
    }
    
    // Define other methods and classes here
    public void WriteToLog(Object source, System.Timers.ElapsedEventArgs e)
    {
        var myString = "Put your logging data here: " + DateTime.Now.ToString();
        try
        {
            using (StreamWriter file = File.AppendText(@"D:\Log.txt"))
            {
                file.WriteLine(myString);
                file.Flush();
                file.Close();
            }
        }
        catch(Exception ex)
        {
            //Do some error catching here if needed.
        }
    
    }