@manhng

Welcome to my blog!

The process cannot access the file because it is being used by another process

July 8, 2021 13:28

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 filePathstring 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 logFilePathstring 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)

c# - Will lock prevent the error "The process cannot access the file because it is being used by another process"? - Stack Overflow

Async Waiting inside C# Locks (cdemi.io)

Categories

Recent posts