Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Visual Basic
Expertise: Intermediate
Feb 24, 1999

Quirks of the Dir$ Function

If you use the intrinsic VB Dir$ function to check for the existence of a certain file, then subsequently try to remove the directory where the file is found using the VB RMDir statement, you get the error 75, "Path/File access error." This error occurs even if you kill the file prior to removing the directory.

You can see the problem if you manually create a directory and file with the names c:\dummy\bla-bla.txt. Then try to go step-by-step through this sample code to see what's going on:

Private Sub Command1_Click()
	If Dir$("C:\dummy\bla-bla.txt") = "" Then
		'do nothing, file is not found
		'kill the file and remove the directory
		Kill "C:\dummy\bla-bla.txt"
		RmDir "C:\dummy"
	End If 
End Sub 

The statement RmDir "C:\dummy" causes error 75 because this directory is locked and cannot be removed.

To work around this problem, check for the existence of a file by trying to open it for sequential/random/binary (anything should work) access and close it immediately afterwards. If this file exists, your routine will proceed with its code, where you can kill the file and remove the directory. A trappable error 53, "File not found", indicates the file does not exist. After you trap the error, you can re-direct the execution of your code as required. This code is a good example to start with:

Private Sub Command1_Click()
	Dim FHandle As Long
	Dim FileNAme As String
	FileNAme = "C:\dummy\bla-bla.txt"
	FH = FreeFile
	On Error Goto ErrHadler
	Open FileNAme For Input As FHandle
	Close FHandle
	Kill FileNAme
	RmDir "C:\dummy" 

Exit Sub 

	Select case Err
	Case 53 'File not found
		Resume CleanUp
	Case Else
		'display error info
	End Select 
End Sub 

You can't use Sequential Access for Output or Append. If the file does not exist, it is created automatically when the Open statement executes, and all your code loses sense.

Also note that the RmDir statement causes error 75, "Path/File access error", if you try to remove a directory that's not empty. Kill all the files one by one prior to removing a directory, or opt to use an API to do the job.

Of course, you would never want to go to this extreme unless you find that there's no alternative. This is an incredibly bizarre behavior, and most apps would never be affected by it.

Brian Hunter
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date