How to use System.IO.File.Open, yet be able to AppendText?

CB 46 Reputation points
2021-08-10T19:52:56.657+00:00

My app updates a log .csv file periodically. I read the docs which suggested this approach:

                using (StreamWriter sw = File.AppendText(filenameWithPath))
                {
                    sw.WriteLine(someText);
                }

Works fine. The problem is the user wants to open the log, when they do the app crashes because the files locked.
I've been trying to work out what to do about that. I want to hold it open so I tried this:

                fs =File.Open(filenameWithPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read);

sr = new StreamWriter(fs);

This creates the file, locks it to others, perfect.. except!!!

sr.WriteLine(data); doesnt write any data! The file is always empty.

What could be going wrong, or what is the right way to do this using the using statement?
Thanks

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,408 questions
{count} votes

Accepted answer
  1. Sam of Simple Samples 5,516 Reputation points
    2021-08-10T22:03:00.7+00:00

    Are you flushing the file, as in StreamWriter.Flush? The using statement does that automatically so that is probably why you are not familiar with flush. StreamWriter.Close will also flush. The documentation of that says that implementation of Close calls the Dispose method also. The Dispose method is important; without calling it the file remains locked and other applications will be unable to open the file (until it is disposed, including the end of the application).


1 additional answer

Sort by: Most helpful
  1. Karen Payne MVP 35,201 Reputation points
    2021-08-10T22:14:37.07+00:00

    Conceptually here are two code samples, first will get a in use error while the second does not.

    [TestMethod]
    [TestTraits(Trait.FileOperations)]
    [ExpectedException(typeof(IOException), "user message.")]
    public async Task FileInUseExample2()
    {
    
        if (!File.Exists(FileInUseName))
        {
            File.Create(FileInUseName);
        }
    
        await using StreamWriter writer = new StreamWriter(FileInUseName);
        await writer.WriteLineAsync("Hello");
    
    }
    
    /// <summary>
    /// Create and write to a file done right as appose to <see cref="FileInUseExample2"/>
    /// </summary>
    /// <returns>Nada</returns>
    [TestMethod]
    [TestTraits(Trait.FileOperations)]
    public async Task FileInUseExample1()
    {
    
        File.Create(FileInUseName).Close();
    
        await Task.Delay(500);
    
        await File.WriteAllTextAsync(FileInUseName, "Hello");
    
    }