Recipe 12.3. Creating a New Directory


Problem

You need to create a new directory to store user or application data.

Solution

Sample code folder: Chapter 12\NewDirectory

Use the My.Computer.FileSystem. CreateDirectory() method to create the new directory. Pass the method a String containing the directory path to create.

Discussion

To try out this feature, create a new Windows Forms application, and add a TextBox control named TextBox1 and a Button control named Button1 to the form. Now add the following code to the form's class template:

 Private Sub Button1_Click(ByVal sender As System.Object, _       ByVal e As System.EventArgs) Handles Button1.Click    ' ----- The user must supply a directory.    If (Trim(TextBox1.Text) = "") Then       MsgBox("Please supply a directory.")       TextBox1.Focus( )       Exit Sub    End If    ' ----- Create the directory requested by the user.    If (My.Computer.FileSystem.DirectoryExists( _          TextBox1.Text)) Then       MsgBox("The directory already exists.")    Else       Try          My.Computer.FileSystem.CreateDirectory(TextBox1.Text)          MsgBox("Directory created successfully.")       Catch ex As Exception          MsgBox("The directory could not be created due " & _             "to the following error:" & _             vbCrLf & vbCrLf & ex.Message)       End Try    End If End Sub 

The CreateDirectory( ) method accepts either absolute or relative paths in drive-letter or UNC format, but not URL-based "file://" paths. If the directory cannot be created, CreateDirectory( ) generates an exception.

A variation of this method exists through the System.IO.Directory.CreateDirectory( ) function. This function returns a System.IO.DirectoryInfo object for the newly created directory object. It also includes a second overload that accepts security settings for the new directory.




Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net