To determine whether a file is locked or in use by another process, you generally attempt to
open the file exclusively. If it's locked by another process, the operation will fail with an
IOException (or equivalent) which you can catch.
Here’s how to do it in common languages:
C# (.NET)
using System;
using System.IO;
public static bool IsFileLocked(string filePath)
{
FileStream stream = null;
try
{
stream = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
return false; // File is not locked
}
catch (IOException)
{
return true; // File is locked or in use
}
finally
{
stream?.Close();
}
}
FileShare.None ensures exclusive access.
If the file is locked (e.g., by Excel or another process), an IOException is thrown.
Java
import java.io.*;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
public static boolean isFileLocked(File file) {
try (RandomAccessFile raf = new RandomAccessFile(file, "rw");
FileChannel channel = raf.getChannel();
FileLock lock = channel.tryLock()) {
if (lock == null) {
return true; // Couldn't get the lock
}
return false; // Lock acquired
} catch (IOException e) {
return true; // File is locked or inaccessible
}
}
tryLock() returns null if the file is already locked.
Handles exclusive access check.
Python
import os
def is_file_locked(filepath):
if not os.path.exists(filepath):
return False
try:
with open(filepath, 'a'):
return False # File is not locked
except IOError:
return True # File is locked or in use
This test works well on Unix-like systems.
On Windows, you may need additional tools like pywin32 for more accurate lock status.
Notes and Limitations
File locks are advisory, not mandatory on most systems (especially Unix).
This method checks whether you can acquire an exclusive handle — it's the most practical way to check locks.
There is no built-in method to ask the OS "who is locking this file" without external tools.
Optional: See Which Process Is Locking the File
Windows: Use handle.exe from Sysinternals:
handle.exe "filename.txt"
Linux/macOS: Use lsof:
lsof filename.txt
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
To determine whether a file is locked or in use by another process, you generally attempt to open the file exclusively. If it's locked by another process, the operation will fail with an
IOException(or equivalent) which you can catch.Here’s how to do it in common languages:
C# (.NET)
FileShare.Noneensures exclusive access.IOExceptionis thrown.Java
tryLock()returnsnullif the file is already locked.Python
pywin32for more accurate lock status.Notes and Limitations
Optional: See Which Process Is Locking the File
Windows: Use
handle.exefrom Sysinternals:Linux/macOS: Use
lsof: