The process cannot access the file because it is being used by another process (edit)
The process cannot access the file '{path}' because it is being used by another process
public class Logger {
private static ReaderWriterLockSlim _readWriteLock = new ReaderWriterLockSlim();
public void WriteToFileThreadSafe(string text, string path) {
// Set Status to Locked
_readWriteLock.EnterWriteLock();
try {
// Append text to the file
using (StreamWriter sw = File.AppendText(path)) {
sw.WriteLine(text);
sw.Close();
}
} finally {
// Release lock
_readWriteLock.ExitWriteLock();
}
}
}
MSDN ReaderWriterLockSlim
ReaderWriterLockSlim Class (System.Threading) | Microsoft Docs
Snippet
public static class Logger { public static void Log(string filePath, string message) { using (StreamWriter sw = new StreamWriter(filePath, true, Encoding.UTF8)) { sw.WriteLine(message); sw.Close(); } } }
Snippet
public static class Logger { private static object locker = new object(); public static void Log(string logFilePath, string message) { lock (locker) { using (FileStream file = new FileStream(logFilePath, FileMode.Append, FileAccess.Write, FileShare.None)) { StreamWriter writer = new StreamWriter(file); writer.Write(message); writer.Flush(); file.Close(); } } } }
Thread Safe File Write C# - Wait On Lock — (B)logs of Johan Dörper (johandorper.com)