DirectoryThe Directory class exposes routines for creating, moving, and enumerating through directories and subdirectories. This class cannot be inherited. Instances of the Directory class can enumerate through themselves , returning file or directory objects as appropriate. Directories can be defined as read-only or hidden. This section talks about and shows examples for creating, deleting, examining the existence of, enumerating, and getting information for directories. Each of these code examples can be found in a single page of the book's supporting Web site. To find the examples, go to http://www.usingasp.net/SysIO/WebForm1.aspx. Ensuring a Usable Directory NameBefore I let users create and delete directories on my server, I must be sure they don't do something such as delete C:\WINNT or C:\WINNT\SYSTEM32. To prevent such mischief, I created a method that examines the directory name that the user entered to make sure it won't really mess up my Web server. If the directory has a forward slash, a backslash, or a colon (/, \, or :), I don't allow its use. That way, users can type in only a single directory name, and not a compound directory such as MyDirectory/Pictures/OtherStuff. They also can't type in a drive letter such a C:\ThisIsFun\HereWeGo. The following method examines the text string to be sure that the path the user has entered is okay to use: Public Function IsPathOK() As Boolean Dim strDirectory As String strDirectory = DirectoryName.Text Result.Text = "The directory you specified has illegal characters." If strDirectory.IndexOf("\") >= 0 Then Return False ElseIf strDirectory.IndexOf("/") >= 0 Then Return False ElseIf strDirectory.IndexOf(":") >= 0 Then Return False End If Result.Text = "" Return True End Function Creating DirectoriesIt's not common to create directories from a Web application, but I've encountered the need. I once wrote an application in which subscribers could post their own content to a set of HTML pages. To separate the content of each subscriber, I had to be sure that the content for each subscriber was in a different directory. This meant that I had to create a directory each time a subscriber was added. I automated the task so that the Web application administrators could do it from a Web page, and not have to create a directory from the server's console. Creating a directory is easy. All you need to do is call the static Directory.CreateDirectory() method. It takes a single string argument that contains a directory name. The following code shows how to create a directory: Dim strDirectory as String strDirectory = "C:\Test\One\Two" Directory.CreateDirectory( strDirectory ) Note that the preceding code doesn't implement a Try / Catch block. I omit them for clarity for the code snippets in this chapter, but you can see Try / Catch blocks in the full code examples that I used for the www.UsingASP.net live examples. Note In many of the examples in this chapter, I use the Server.MapPath() method. This method provides a way to supply a full path relative to the current directory, even if the current directory is not known. Figure 5.1 shows the example code being used to create a directory named RickLeinecker. Listing 5.1 shows the code used to create the directory. The resulting directory can be seen in a label control, and in this case is E:\InetPub\UsingASPNet\SysIO\ UserCreatedDirectories\RickLeinecker. Figure 5.1. Creating directories can also be done with the Directory class.
Note I created the directory E:\InetPub\UsingASPNet\SysIO\UserCreatedDirectories with write permissions so that the examples would run correctly. Listing 5.1 Creating a Directory for Your Sample ApplicationSub CreateDirectory_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) ' Call the code that checks for invalid characters. If Not IsPathOK() Then Return End If ' Create the directory path. Dim strFilepath As String strFilepath = _ Server.MapPath("UserCreatedDirectories\" & DirectoryName.Text) ' Create the directory and catch exceptions. Try Directory.CreateDirectory(strFilepath) Result.Text = "Created: " & strFilepath Catch ex As Exception Result.Text = "Exception: " & ex.Message End Try End Sub Caution I've gotten into the habit over the years of naming exceptions e in the catch block. This is in conflict with the .NET custom of naming event argument variables e . When I first tried catching exceptions in my code, I named them e and spun my wheels for a bit figuring out why the code wouldn't compile. (It would have helped to have a meaningful compiler message.) Deleting DirectoriesIt probably will be rare for your application to need to delete directories, but the capability is there from the Directory class all the same. To delete a directory, you call the Directory.Delete() method with a single string argument containing the directory that you want to delete. The following code shows how to delete a directory using the Directory class: Dim strDirectory as String strDirectory = "C:\Test\One\Two" Directory.Delete( strDirectory ) Figure 5.2 shows the sample application on www.UsingASP.net after a directory has been deleted, and you can see the code that accomplishes this in Listing 5.2. Figure 5.2. Deleting directories can be a risky choice, but sometimes it's necessary.
Listing 5.2 Deleting a Directory in Your Sample ApplicationSub DeleteDirectory_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) ' Call the code that checks for invalid characters. If Not IsPathOK() Then Return End If ' Create the directory path. Dim strFilepath As String strFilepath = _ Server.MapPath("UserCreatedDirectories\" & DirectoryName.Text) ' Delete the directory and catch exceptions. Try Directory.Delete(strFilepath) Result.Text = "Created: " & strFilepath Catch ex As Exception Result.Text = "Exception: " & ex.Message End Try End Sub Testing for the Existence of a DirectoryEarlier in this chapter I mentioned an application I wrote in which I created separate directories for each subscriber. Before creating a directory, though, I had to be sure it didn't already exist. Trying to create a directory that already exists generates an error, and it's almost always better to anticipate a problem than to react to an error. For this reason, I checked for the existence of the target directory before attempting to create it. The Directory class offers an easy way to check the existence of a directory. All you need to do is call the Directory.DirectoryExists() method with a single string argument containing the directory you want to test. The following code shows how to check for a directory named C:\MyTest\ThisBook: Dim strDirectory as String strDirectory = "C:\MyTest\ThisBook" If Directory.DirectoryExists( strDirectory ) Then ' The directory does exist. Else ' The directory does not exist. End If Figure 5.3 shows the sample application looking for a directory named DataFiles (which really exists as the fully qualified path E:\InetPub\UsingASPNet\SysIO\ UserCreatedDirectories\DataFiles). Listing 5.3 shows the code that performs the task. Figure 5.3. Many times it's necessary (or just plain good sense) to test for the existence of a directory.
Listing 5.3 Checking for Existing Directories in Your Sample ApplicationPrivate Sub DirectoryExists_Click(ByVal sender As System.Object, ByVal e As System. EventArgs) _ Handles DirectoryExists.Click ' Call the code that checks for invalid characters. If Not IsPathOK() Then Return End If ' Create the directory path. Dim strFilepath As String strFilepath = Server.MapPath("UserCreatedDirectories\" & DirectoryName.Text) ' Check the existence the directory and catch exceptions. Try If Directory.Exists(strFilepath) = True Then Result.Text = strFilepath & " does exist" Else Result.Text = strFilepath & " does not exist" End If Catch ex As Exception Result.Text += "Exception: " & ex.Message End Try End Sub Getting a List of DirectoriesAt times it is necessary to enumerate directories. You might need to create a list of directories for an administrative menu, or just present the list as information to users. The Directory class has a method named GetDirectoriesInDirectory() . This method returns a collection of Directory classes. Note A single directory can be declared and referenced as follows : Dim dr as Directory A collection of directories can be declared as follows: Dim drs as Directory() You can act on a Directory class as you'd expect with method calls such as Directory.CallAMethod() , but there's a special syntax that makes it easy to loop through a collection of Directory classes as follows: Dim dr as Directory 'Dim drs as Directory() ' Here we'll do something to populate the Directory collection For Each dr in drs ' Use the Directory class named dr Next Figure 5.4 shows the sample application enumerating the directories, and Listing 5.4 shows the code that performs the task. Figure 5.4. Getting a list of directories that are contained in a directory is easy with the Directory class.
Listing 5.4 Obtaining a Collection of Directory Classes with the GetDirectoriesInDirectory() MethodPrivate Sub GetDirsInDir_Click(ByVal sender As System.Object, ByVal e As System. EventArgs) Handles GetDirsInDir.Click Dim dl As String() Dim Item As String Try dl = Directory.GetDirectories(Request.MapPath("UserCreatedDirectories"), "*.*") Result.Text = "" For Each Item In dl Dim strDirName As String strDirName = Item Dim nIndex As Integer nIndex = strDirName.IndexOf("\") While nIndex >= 0 strDirName = Right(strDirName, Len(strDirName) - nIndex - 1) nIndex = strDirName.IndexOf("\") End While Result.Text = Result.Text & strDirName & _ " " & Chr(13) & Chr(10) Next Catch ex As Exception Result.Text = ex.Message End Try End Sub Listing Files in a DirectoryThe Directory class provides an easy way to list the files in a directory. All you must do is call the Directory.GetFilesInDirectory() method with a single string argument that contains the name of the directory. The following code shows how to do this: Dim fl as String() Dim strDir As String strDir = "c:\Test\Of\This" fl = Directory.GetFiles( strDir ) It's important to note in the preceding code snippet that the Directory.GetFilesInDirectory() method returns a collection of Files classes. You can easily loop through the collection with the For / Each construct, as shown in the note in the preceding section, which showed how to loop through a collection of Directory classes. Figure 5.5 shows the sample application listing the files in the E:\InetPub\UsingASPNet\ SysIO directory. The code for the example can be seen in Listing 5.5. Figure 5.5. Getting a list of files that are contained in a directory is easy with the Directory class.
Listing 5.5 Using the Directory Class to List Files in the Current DirectoryPrivate Sub GetFilesInDirectory_Click(ByVal sender As System.Object, ByVal e As System. EventArgs) _ Handles GetFilesInDirectory.Click Dim fl As String() Dim Item As String fl = Directory.GetFiles(Request.MapPath(".")) Result.Text = "" For Each Item In fl Dim strDirName As String strDirName = Item Dim nIndex As Integer nIndex = strDirName.IndexOf("\") While nIndex >= 0 strDirName = Right(strDirName, Len(strDirName) - nIndex - 1) nIndex = strDirName.IndexOf("\") End While Result.Text = Result.Text & strDirName & " " & Chr(13) & Chr(10) Next End Sub Listing Logical DrivesIt's unlikely that you'll provide your users with a list of logical drives, but some of your administrative functionality might require it. For example, if you have an administrative menu where files can be moved or copied , you might want to provide a list of the logical drives that can be found on the server. The Directory class provides a method named GetLogicalDrives() that returns a collection of strings, each of which contains a drive designation. Figure 5.6 shows this functionality in operation in the example, and Listing 5.6 shows the code that makes it happen. Figure 5.6. Finding a list of valid logical drives can help you develop applications with choices.
Listing 5.6 Getting and Displaying a List of Logical DrivesSub GetLogicalDrives_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Dim strDrives As String() Dim Item As String strDrives = Directory.GetLogicalDrives() Result.Text = "" For Each Item In strDrives Result.Text = Result.Text & Item & "<br>" & Chr(13) & Chr(10) Next End Sub Getting Directory InformationThe last thing to cover with regard to directories is the capability for the Directory class to return information about a named directory. Figure 5.7 shows the sample application displaying information about the E:\InetPub\UsingASPNet\SysIO directory, and Listing 5.7 shows where a method named CurrentDirectoryInfo() can be seen. Figure 5.7. Sometimes it's helpful to gather information about a directory.
Listing 5.7 Showing Information About a DirectoryPrivate Sub CurrentDirectoryInfo_Click(ByVal sender As System.Object, ByVal e As System. EventArgs) _ Handles CurrentDirectoryInfo.Click Dim strCurrentDir As String = Directory.GetCurrentDirectory() Result.Text = "Current:" & strCurrentDir & _ " " + vbCrLf Result.Text = Result.Text & "Created: " & Directory.GetCreationTime(strCurrentDir) & _ " " + vbCrLf Result.Text = Result.Text & "LastAccess: " & Directory.GetLastAccessTime( strCurrentDir).ToFileTime() & _ " " + vbCrLf Result.Text = Result.Text & "LastWrite: " & Directory.GetLastWriteTime(strCurrentDir). ToFileTime() & _ " " + vbCrLf End Sub |