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).
How to use System.IO.File.Open, yet be able to AppendText?

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
-
Sam of Simple Samples 5,551 Reputation points
2021-08-10T22:03:00.7+00:00
1 additional answer
Sort by: Most helpful
-
Karen Payne MVP 35,561 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"); }