C# Error 02: The process cannot access the file because it is being used by another process in C# ?
The error "The process cannot access the file because it is being used by another process" happens when multiple parts of your program (or another program) try to open the same file without proper access control.
✅ Solutions
1️⃣ Use FileStream
with FileShare
to allow multiple accesses
Modify WriteLog()
to open and close the file properly:
using System;
using System.IO;
class Program
{
static void Main()
{
string logFilePath = $"{DateTime.Now:dd-MM-yyyy HH_mm_ss}.log";
// Write logs
WriteLog(logFilePath, "Application started.");
WriteLog(logFilePath, "Processing data...");
WriteLog(logFilePath, "Application finished.");
}
static void WriteLog(string filePath, string message)
{
string logEntry = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss} | {message}";
// ✅ Properly handle file access with FileStream
using (FileStream fs = new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.Read))
using (StreamWriter writer = new StreamWriter(fs))
{
writer.WriteLine(logEntry);
}
}
}
✅ FileShare.Read
allows other processes to read the file while it is open.
2️⃣ Ensure the File is Properly Closed
If the file is open in another part of your program, ensure:
- You're using
using
statements forStreamWriter
andFileStream
. - No other part of your program is keeping the file open.
3️⃣ Check If Another Program is Locking the File
- Make sure the log file is not open in:
- Notepad
- Excel
- Any other text editor
- Close the file and try running the program again.
4️⃣ Use Thread.Sleep()
Before Retrying
If multiple processes are writing logs, retry after a short delay:
static void WriteLog(string filePath, string message)
{
int retryCount = 5;
while (retryCount > 0)
{
try
{
using (FileStream fs = new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.Read))
using (StreamWriter writer = new StreamWriter(fs))
{
writer.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss} | {message}");
}
break; // Exit loop if write is successful
}
catch (IOException)
{
retryCount--;
System.Threading.Thread.Sleep(100); // Wait 100ms before retrying
}
}
}
✅ This prevents crashes if the file is temporarily locked.
🚀 Best Practice: Use a Logging Library (NLog, Serilog, log4net)
Instead of manually handling logs, use NLog
or Serilog
, which handle concurrency better:
var logger = NLog.LogManager.GetCurrentClassLogger();
logger.Info("Application started");
0 Comments