- 1 year ago
Check if file in the shared folder is not opened by another process
To check if a file in a shared folder is not opened by another process in Delphi, you can use the TFileStream
class and attempt to open the file in exclusive mode. If the file is already opened by another process, an exception will be raised, indicating that it is not available for exclusive access. Here's an example:
delphiuses
SysUtils, Classes;
function IsFileAvailable(filePath: string): Boolean;
var
fileStream: TFileStream;
begin
try
// Attempt to open the file in exclusive mode
fileStream := TFileStream.Create(filePath, fmOpenReadWrite or fmShareExclusive);
fileStream.Free;
Result := True; // File is available and not opened by another process
except
on E: EFOpenError do
Result := False; // File is opened by another process
end;
end;
In the IsFileAvailable
function, we attempt to open the file specified by filePath
using TFileStream
with the fmOpenReadWrite
and fmShareExclusive
flags. If the file is already opened by another process, an EFOpenError
exception will be raised.
To use this function, you can call it with the path to the shared file you want to check, and it will return True
if the file is available (not opened by another process) and False
if it is opened by another process.
Example usage:
delphivar
filePath: string;
isAvailable: Boolean;
begin
filePath := '\\server\shared\file.txt';
isAvailable := IsFileAvailable(filePath);
if isAvailable then
ShowMessage('The file is available.')
else
ShowMessage('The file is opened by another process.');
end;
Replace '\\server\shared\file.txt'
with the actual path of the file you want to check.
Please note that this approach only checks if the file is opened in exclusive mode. If the file is opened with shared access by another process, it will still be considered available.