Open Sesame

As you develop more and more scripts, you’re bound to find yourself working with files. Often, the easiest thing to do is to hard code a filename that we want to open and use. Or we may provide a run time parameter for a file name. Wouldn’t it be nice to be give the user an option to browse for the file like other Windows apps? If your script is running on Windows XP or Windows 2003, you can use the SAFRCFileDlg object.

This object has one property (Filename) and one method (OpenFileOpenDlg). Here’s a short script that demonstrates how to use this object.

OpenFileDemo.vbs
myfile=OpenFile()
wscript.echo “Opening ” & myfile

‘**********************************
‘*  Open File Function               *
‘**********************************
Function OpenFile()
    On Error Resume Next
    Dim objDialog
    ‘This requires Windows XP/2003
    Set objDialog=CreateObject(“SAFRCFileDlg.FileOpen”)
    objDialog.OpenFileOpenDlg
    OpenFile=objDialog.FileName
End Function

This function will return what ever is entered in the dialog box as objDialog.FileName. A user could simply mistype a filename in the dialog box. You’ll still want to verify the existence of the file with the FileSystemObject before doing anything with it.

I wish there was someway to populate a default or specify a starting directory. It appears the object itself has no interface for this and will open to the last directory used. I’ve tried to find a workaround, but it looks like this would involve mucking around with binary registry entries so I guess I’ll live with it.

What about saving a file?  I’ll show you that another day.