Log In    |    Knowledge Base    |    4D Home
Tech Tip: Determining if a file on disk is open or locked
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: 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.

If(Count parameters>0)
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

$OldErrorHandler_T:=Method called on error

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
If(Test path name($SRC_PathName_T)=Is a document)
  MOVE DOCUMENT($SRC_PathName_T;$DST_PathName_T)
   DELAY PROCESS(Current process;15)
  End if
 Until ((Error=0) | ((Tickcount-$Ticks_L)>60))
End if

 If(Test path name($SRC_PathName_T)=Is a document )
 End if

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

ON ERR CALL($OldErrorHandler_T)