Preface
In Windows application development, file operations are one of the very common and important functions. However, in a multi-process or multi-threaded environment, a file may be accessed by multiple programs at the same time, resulting in the problem of "the file has been occupied by other processes". In this case, the program cannot read and write the file normally. At the least, an exception will be thrown, and at the worst, data will be lost or damaged.
In order to solve this problem, developers need to have the ability to judge whether the file is occupied by other processes and make reasonable processing strategies based on this. This article will introduce aThe underlying API function is provided to detect file occupancy status and provides complete C# sample code to help developers improve the robustness and stability of their programs.
text
What is a file occupied by a process?
When a program opens a file exclusively (such as usingHowever, sharing permissions are not set), the operating system will lock this file to prevent other programs from accessing it. At this time, if another program tries to read and write the file, an error "The process cannot access the file because it is being used by another process."
Common scenarios include:
Multiple users/processes operate the same log file at the same time;
Backend services and front-end interface operate configuration files together;
The file browser and the editor open the same document at the same time, etc.
therefore,Determine whether the file is occupiedIt is the first step to solve this kind of problem.
How to determine whether the file is occupied?
Windows systems provide rich APIs to handle file system-related underlying operations. in,In-house
CreateFile
、_lopen
、CloseHandle
The other function can be used to try to access a file and detect its status.
Recommended practice: Use _lopen and CloseHandle
We can call_lopen
The function tries to open the file read-only or read-write. If an invalid handle is returned, it means that the file may have been opened exclusively by other processes.
Here is the complete C# implementation code:
using System; using ; using ; public class FileStatus { [DllImport("")] private static extern IntPtr _lopen(string lpPathName, int iReadWrite); [DllImport("")] private static extern bool CloseHandle(IntPtr hObject); private const int OF_READWRITE = 2; private const int OF_SHARE_DENY_NONE = 0x40; private static readonly IntPtr HFILE_ERROR = new IntPtr(-1); /// <summary> /// Check whether the file is occupied by other processes /// </summary> /// <param name="fileFullName">Full path of file</param> /// <returns>0: Not occupied; 1: occupied; -1: The file does not exist</returns> public static int FileIsOpen(string fileFullName) { if (!(fileFullName)) { return -1; // The file does not exist } IntPtr handle = _lopen(fileFullName, OF_READWRITE | OF_SHARE_DENY_NONE); if (handle == HFILE_ERROR) { return 1; // Files are occupied } CloseHandle(handle); // Close the handle to avoid resource leakage return 0; // The file is not occupied } }
Parameter description
OF_READWRITE
: means to open the file by reading and writing.
OF_SHARE_DENY_NONE
: Allow other processes to read and write files at the same time.
If the return value isHFILE_ERROR
, it means that the file is currently occupied.
Optional: Use FileStream to try to open a file
In addition to calling the Windows API, you can also use the standard class library provided by .NET to make simple judgments:
public static bool IsFileLocked(string filePath) { try { using (FileStream fs = (filePath, , , )) { (); } } catch (IOException) { // Files are occupied return true; } return false; }
Although this method is simpler, it is not as accurate and efficient as the API method in some complex scenarios.
Summarize
When performing file operations on Windows platform, it is an issue that cannot be ignored to determine whether the file is occupied by other processes. Especially in a multi-process and multi-threaded environment, the rational detection and processing of file locking situations will help improve the stability of the program and user experience.
By callingThe underlying API method provided (such as
_lopen
andCloseHandle
), we can efficiently and accurately determine whether the file is in an occupied state. At the same time, combined with the standard .NET class libraryFileStream
Technology can also be used as an auxiliary means to make simple judgments.
Whether it is developing WinForm applications, WPF interface projects, or background service programs, mastering these file status detection techniques will be of great benefit to your development work.
suggestion: In actual development, it is recommended to give priority to using API for file occupation detection, especially in scenarios where frequent inspections are required or performance requirements are high.
If you need to further expand your functions, such as obtaining process information that specifically occupies the file, you can also use WMI or third-party libraries (e.g.Sysinternals
) to conduct in-depth analysis.
at last
This is the article about whether C# detects whether a C# file is occupied by a process. For more relevant content on whether a C# test file is occupied, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!