KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: Determining if a file on disk is open or locked
PRODUCT: 4D | VERSION: 11 | PLATFORM: Mac & Win
Published On: November 12, 2008
Your current browser may not allow you to download the asset. We recommend Mozilla Firefox or Google Chrome.
Log In

Often the need arises to open, move, or delete a file on disk. Unfortunately there is no direct way within 4D to determine if the file is locked. But there is an indirect way for you to programmatically handle the situation.

If 4D attempts one of numerous operations on an external file, such as open, move, delete, or rename, the operating system can return one of 30 possible errors. The complete list of these errors can be found under "OS File Manager Errors" in chapter 68 - Error Codes of the 4th Dimension Language Reference at: https://www.4d.com/docs/CMu/CMU02028.HTM. A technique of using a customized error handling method in combination with 4D's system variable "Error" can provide a robust method of handling the situation.

First create a method to be installed with ON ERR CALL before any file manipulation. In this tech tip, moving and renaming a file will be used as an example. In this case, the error handler only captures the system variable "Error". This method also prevents 4D from displaying itís own error dialog box.

C_LONGINT(Error;$1)
If(Count parameters>0)
  Error:=$1
End if


Next initialize the system variable "Error" to zero and capture any installed error handler so we can return it to handling other errors when done.

Error:=0 `// Init the system variable Error to zero

C_TEXT($OldErrorHandler_T)
$OldErrorHandler_T:=Method called on error
ON ERR CALL(EMPTY_HandleError)


Now to attempt to move and rename some files. This routine assumes that any file currently in use will only be used for a very short period of time and will then be closed and freed.

 `// Rename and move the existing file
$DST_PathName_T:=$DST_PathName_T+String(Tickcount)+"_"+$FileName_T+".txt"
If(Test path name($SRC_PathName_T)=Is a document)
 $Ticks_L:=Tickcount
 Repeat
  Error:=0
  MOVE DOCUMENT($SRC_PathName_T;$DST_PathName_T)
  If(Error#0)
   DELAY PROCESS(Current process;15)
  End if
 Until ((Error=0) | ((Tickcount-$Ticks_L)>60))
End if

If(Error=0)
 If(Test path name($SRC_PathName_T)=Is a document )
  DELETE DOCUMENT($SRC_PathName_T)
 End if

 If(Test path name($FilePath_T+$FileName_T+".txt")#Is a document )
  $SRC_PathName_T:=$FilePath_T+$FileName_T+"_New.txt"
  If(Test path name($SRC_PathName_T)=Is a document )
   $DST_PathName_T:=$FilePath_T+$FileName_T+".txt"
   MOVE DOCUMENT($SRC_PathName_T;$DST_PathName_T)
  End if
 End if
End if

ON ERR CALL($OldErrorHandler_T)