Scripting with Visual Basic
When programming in Windows (R) environment, scripting might come in quite handy. Usually scripting is accomplished through writing vbscript, jscript or wscript program files that contain the instructions needed to be executed by script engine. Once a script file is dubugged and saved it can be executed. You, as a Visual Basic programmer can use the power of scripting from your own Visual Basic applications. One area where scripting can come in very handy is file manipulations. I will show you how you can move and delete files using Microsoft (R) Scripting runtime from Visual Basic.
First of all, to be able to use scripting runtime you have to add a reference to it. To do that, start the application that will use the runtime. (Start a new project if you want just to try runtime first). Once the project is loaded, go to Project menu and click on References... . A references dialog box should appear. Find "Microsoft Scripting Runtime" and click on it. Press OK. The reference to runtime has been added. Now to our example.
Create a file called test.txt and place it in drive c:\. This will be our test file that i will use to demonstrate a one very simple function of scripting runtime. Now, in the Visual Basic project open the main form and add a button and call it cmdCopy. I will add the code to this button so that when pressed it will copy test.txt from c:\ to d:\. Also add another button that will delete the copy you just moved and call it cmdDelete.
When performing any file manipulation with scripting runtime (that's what we are going to do) you need an instance of FileSystemObject. In my example, I declared a private variable called fso of type FileSystemObject to get that instance:
Private fso As
Don't forget to unload the instance to prevent memory leaks:
Private Sub Form_Unload(Cancel As Integer)
Private Sub cmdCopy_Click()
To delete just newly copied file, code cmdDelete button:
Private Sub cmdDelete_Click()
Copying files is not the only operation you can perform with FileSystemObject. There is so much more functionality to explore. To obtain complete list of functions you can use with Scripting Runtime press F2 while in Visual Basic to get Object Browser and browse through Scripting library. To prove to you that there is much more to scripting power than just plain file copying, let's expand our current application to show the information of a "c" drive on your machine (or which ever drive you wish). Add another command button and name it cmdDrives. Also add expanded text box and name it txtDrive. Make sure that the Multiline property of txtDrive is set to True. After you added the controls, here is the code that when the cmdDrives is pressed outputs the drive letter, file system, drive type and free space of the drive in txtDrive text box:
Private Sub cmdDrives_Click()