Your code, a build or a Windows task fails with IOException: The process cannot access the file 'path' because it is being used by another process. The message means another handle on that file is open with a share mode that does not allow your request. That handle can belong to another program, to another thread in your own app, or to a stream you forgot to close. This post shows how to find out which, and the four fixes that cover almost every case: close the other handle, dispose your streams, allow sharing with FileShare, and retry short-lived locks.
The C# examples were compiled and run on .NET SDK 10.0.401 on macOS. The Windows tools section is based on Microsoft documentation and was not run here.

- Reproduce the error and read the message
- Resolution: what holds the file?
- Solution 1: the file may be in use by some other process
- Solution 2: implement IDisposable for file handles
- Solution 3: choose FileShare and lock threads in your own app
- Solution 4: implement a retry pattern for file processing
- Common errors and what was tested
- Summary
- FAQ
Reproduce the error and read the message
The smallest reproduction is two handles on one file. The first opens it with FileShare.None and keeps it open, the second tries to read:
var held = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
try { File.ReadAllText(path); }
catch (IOException ex) { Console.WriteLine(ex.Message); }
held.Dispose();
Console.WriteLine(File.ReadAllText(path)); // works after Dispose
Real output on .NET 10: The process cannot access the file '<path>' because it is being used by another process., and after Dispose the read succeeds. The same test showed that a stream from File.Create blocks other readers while it is open.
The error is not limited to reads. Write, delete, move and copy fail the same way when another handle forbids it.
Resolution: what holds the file?
There are three common causes, and the fix depends on which one you have:
- Another program has the file open (editor, antivirus, backup, a second instance of your service).
- Your own code has it open: a stream that was never disposed, or two threads using the file at once.
- The share mode you or the other side chose does not allow both handles to exist.
Work through the solutions in this order. The first one tells you which cause applies.
Solution 1: the file may be in use by some other process
Find the owner before you change code. On Windows, three tools show which process holds a handle:
| Tool | Best for | Catch |
|---|---|---|
| PowerToys File Locksmith | Right-click a file in Explorer and see the processes using it | Needs PowerToys; run as administrator to see other users’ processes |
Resource Monitor (resmon) | Nothing to install: CPU tab, Associated Handles, search by file name | The handle search can be slow on a busy machine |
| Sysinternals Handle | Command line list of open handles, scriptable | Run elevated to see everything |
Close the owning application normally first. End a process only when you know what it holds, because it may lose unsaved work. If the build fails to copy a .dll into bin, your own app or the debugger is usually still running, so stop it and rebuild.
If no tool shows an owner and the error is intermittent, an antivirus scan or backup job may be holding the file for a few milliseconds. That is the case Solution 4 is for. On macOS and Linux there is no Windows-style mandatory lock, but .NET still enforces FileShare between handles in the same system, which is why the reproduction above fails there too (tested here on macOS). One difference seen in the test: deleting a file that another handle had open succeeded on macOS, whereas Windows commonly refuses it.
Solution 2: implement IDisposable for file handles
A stream that is never disposed keeps its handle until the garbage collector runs, which can be much later. Wrap every file stream, reader and writer in using:
using (FileStream fs = File.Create(path))
{
byte[] info = new UTF8Encoding(true).GetBytes("This is a test file.");
fs.Write(info, 0, info.Length);
} // handle released here
// or the shorter form
using var reader = new StreamReader(path);
string text = reader.ReadToEnd();
The one-line helpers such as File.ReadAllText and File.WriteAllText open and close the file for you, so prefer them for small files. For more on correct file handling, see how to use File in C#: best practices.
Solution 3: choose FileShare and lock threads in your own app
FileShare tells the operating system what other handles may do while yours is open. See the FileShare enumeration reference. The values are None, Read, Write and ReadWrite (plus Delete). A log file that one process writes while another reads it is the standard case for ReadWrite:
using var writer = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
using var sw = new StreamWriter(writer) { AutoFlush = true };
sw.WriteLine("log entry 1");
using var reader = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
using var sr = new StreamReader(reader);
Console.WriteLine(sr.ReadToEnd());
Real output: log entry 1. Both handles must agree: if the first handle was opened with a stricter mode, the second still fails. Readers can see a partly written last line.
Threads inside one app are the other half of the problem. Many tasks appending to the same file need a gate. This test ran 50 concurrent tasks behind a SemaphoreSlim:
var gate = new SemaphoreSlim(1, 1);
async Task AppendAsync(string line)
{
await gate.WaitAsync();
try { await File.AppendAllTextAsync(path, line + Environment.NewLine); }
finally { gate.Release(); }
}
await Task.WhenAll(Enumerable.Range(1, 50).Select(i => AppendAsync($"line {i}")));
The file ended with exactly 50 lines. A SemaphoreSlim protects one process only. Two processes need a share mode, a named mutex or a single writer service. More on this in file lock and unlock in C# (thread-safe).
Solution 4: implement a retry pattern for file processing
Short locks from antivirus, indexers and sync clients clear by themselves. Retry with a growing delay, and retry only the right exceptions. FileNotFoundException and DirectoryNotFoundException derive from IOException, so a plain catch (IOException) would also retry a missing file for no reason:
static async Task<T> RetryAsync<T>(Func<Task<T>> action, int attempts = 5, int baseDelayMs = 50)
{
for (int attempt = 1; ; attempt++)
{
try { return await action(); }
catch (Exception ex) when (ex is IOException and not FileNotFoundException and not DirectoryNotFoundException
&& attempt < attempts)
{
await Task.Delay(baseDelayMs * (1 << (attempt - 1)));
}
}
}
string text = await RetryAsync(() => File.ReadAllTextAsync(path));
In the test another handle with FileShare.None was released after 300 ms. The call kept retrying (50, 100, 200 ms) and then read the file, and a missing file raised FileNotFoundException immediately. After the last attempt the IOException reaches your code, which is what you want. On Windows you can narrow the filter to sharing violations by checking the low 16 bits of ex.HResult for 32 or 33 (this narrowing was not tested here). For a reusable version, see the retry pattern in C#.
Common errors and what was tested
- The error appears only in production. Another service, a backup or antivirus runs there. Use Handle or File Locksmith on that machine, exclude the folder from scanning, and stagger scheduled jobs.
- It happens right after you write a file. A writer or reader you created was not disposed. Check for streams created in a helper and never closed.
- Windows Update shows 0x80070020. That code is the Windows sharing violation error (ERROR_SHARING_VIOLATION). The usual advice is to rule out other programs with a clean boot and retry; this was not reproduced here.
- Not tested: Windows (mandatory locking, the HResult filter, the tools above), network shares and Docker bind mounts. All C# output above was produced on macOS with .NET SDK 10.0.401.
Summary
- Find the owner first: File Locksmith, Resource Monitor or Handle on Windows.
- Dispose every stream and reader; prefer the one-line
Filehelpers for small files. - Use
FileShare.ReadWriteonly when two handles must coexist, and gate threads inside one app. - Retry
IOExceptionwith backoff for short locks, but notFileNotFoundException.
Further reading: FileShare (Microsoft Learn), PowerToys File Locksmith (Microsoft Learn) and Sysinternals Handle (Microsoft Learn).
Found this useful?
Bookmark this page and share it with your team. Get new .NET, cloud and database tutorials in your inbox.
FAQ
What does ‘the process cannot access the file because it is being used by another process’ mean?
Another handle, from another program or from your own code, has the file open with a share mode that blocks your request. It can happen on read, write, delete, move or copy. Close that handle, change the share mode so both can coexist, or retry if the lock is short.
How do I find which process is locking a file?
On Windows use PowerToys File Locksmith from the Explorer context menu, the Resource Monitor handle search, or the Sysinternals Handle tool, preferably elevated so other users’ processes are listed. If nothing shows up and the error is intermittent, a scanner or backup may hold the file only briefly, so add a retry.
What does FileShare.ReadWrite do and when should I use it?
It lets other handles open the file for reading and writing while yours is open, for example a log that one process writes and another reads. Every handle already open must allow the same sharing, and readers can see partly written data.
