0

I'm using Microsoft Visual Studio Professional 2022 (64-bit) - Current Version 17.3.1 to build a Console App with .NET Core 6.

The App appends text to a .csv file, and it runs fine.

When I start the App twice (giving different data input) I get:

"access the file because it is being used by another process"

The function that appends to the .csv files is:

    public static readonly object myAppendLock = new();
    public static void AppendToRocket(string outputFilePath, string data) {
      lock (myAppendLock) {
        try {
          using StreamWriter w = File.AppendText(outputFilePath);
          w.Write(data + "\n");
          w.Flush();
          w.Close();
          w.Dispose();
        } catch (Exception ex) {
          Log.WriteLog("AppendToRocket.txt", $"Error: {ex.Message}");
        }
      }
    }

Please help me to understand why I'm getting the "access" error.

Charles

user274610
  • 509
  • 9
  • 18
  • 2
    To share a lock between multiple processes, you'd need to use something like a named `Mutex`, which uses OS-level APIs to communicate appropriately. See the constructors of `Mutex` that take a `string name` parameter – Marc Gravell Aug 18 '22 at 22:12
  • What about using `FileShare`? – C. Helling Aug 18 '22 at 22:20
  • if you want to see who has the file open use sysinternals 'handle' command – pm100 Aug 18 '22 at 23:05
  • Does this answer your question? [Process and Thread Safe way to write to multiple files](https://stackoverflow.com/questions/73218606/process-and-thread-safe-way-to-write-to-multiple-files) – Charlieface Aug 19 '22 at 00:32

1 Answers1

0

I want to thank C Helling. FileShare was the answer. Here is my working solution:

    public static void AppendToRocket(string outputFilePath, string data) {
      try {
        using FileStream fs = new(outputFilePath,
                                  FileMode.Append, 
                                  FileAccess.Write, 
                                  FileShare.ReadWrite);
        using var writer = new StreamWriter(fs);
        using var syncWriter = TextWriter.Synchronized(writer);
        syncWriter.WriteLine(data);
      } catch (Exception ex) {
        Log.WriteLog("AppendToRocket.txt", $"Error: {ex.Message}");
      }
    }

Charles

user274610
  • 509
  • 9
  • 18