Search code examples
c#fileprocesslockingtextwriter

Locking AppendAllText vs TextWriter


Regarding the preventing of "already in use" errors i want to ask if the first code snippet could potentialy be dangerous if called multiple times from multiple clients? Or are both code blocks equaly safe ?

I am asking because the second codesnippet calls a close method which also does a dispose which sounds safer.

//FIRST
lock (_myLock)
{
    File.AppendAllText(_filePath, text);
}


//SECOND
lock (_myLock)
{
    TextWriter tw = new StreamWriter(_filePath, true);
    tw.Write(text);
    tw.Close();
}

Solution

  • They are both the same. File.AppendAllText calls Dispose too.

    private static void InternalAppendAllText(string path, string contents, Encoding encoding)
    {
        using (StreamWriter writer = new StreamWriter(path, true, encoding))
        {
            writer.Write(contents);
        }
    }