![]() ![]() | ||
You'll find an example showing how to use the File and Directory classes on the CD-ROM. This example is called copier, and it lets you create a directory and then copy a file to that new directory. As discussed in the In Depth section of this chapter, to use the File and Directory classes, I first import the System.IO namespace, then use the Directory class's CreateDirectory method to create a new directory, using the path the user has entered into a text box. Then I use an Open File dialog box to determine what file the user wants to copy, and use the File class's Copy method to actually copy the file:
Imports System.IO Public Class Form1 Inherits System.Windows.Forms.Form 'Windows Form Designer generated code Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Try Directory.CreateDirectory(TextBox1.Text) Catch MsgBox("Could not create directory.") Exit Sub End Try MsgBox("Directory created.") End Sub Private Sub Button2_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button2.Click Try If OpenFileDialog1.ShowDialog <> DialogResult.Cancel Then File.Copy(OpenFileDialog1.FileName, TextBox1.Text & "\" & _ OpenFileDialog1.FileName.Substring(_ OpenFileDialog1.FileName.LastIndexOf("\"))) End If Catch MsgBox("Could not copy file.") Exit Sub End Try MsgBox("File copied.") End Sub End Class
And that's all it takes—I didn't need to open the file, or even create objects of the File and Directory classes. You can see the results of this code after the files has been copied to the new directory in Figure 13.4.
![]() ![]() | ||