asp.net
Figure 2.7
Output of Listing 2.2.1 when viewed through a browser.
When working with the various file system classes, it is often handy to import the System.IO namespace to save unneeded typing (line 1).
Listing 2.2.1 uses the postback form technique we discussed in Chapter 1, "Common ASP.NET Page Techniques." On line 74, a form with the runat="server" attribute is created. In the form, there is an asp:textbox control and a submit button (btnSubmit, line 77). When a user first visits the page, Page.IsPostBack is False and lines 5 and 6 in the Page_Load event handler are executed, displaying an instructional message.
After the user enters a directory name and submits the form, the Page.IsPostBack property is set to True and the code from lines 8 through 39 is executed. On line 9, a DirectoryInfo object, dirInfo, is created. Because the DirectoryInfo class is useful for retrieving information on a particular directory, including the files and subdirectories of a particular directory, it isn't surprising that the DirectoryInfo constructor requires, as a parameter, the path of the directory with which the developer is interested in working. In this case, we are interested in the directory specified by the user in the txtDirectoryName text box.
--------------------------------------------------------------------------------
Note
The DirectoryInfo class represents a specific directory on the Web server's file system; the DirectoryInfo constructor requires that you specify a valid directory path. However, there may be times when you don't want to have to go through the steps of creating an instance of the DirectoryInfo class just to, say, delete a directory. The .NET Framework contains a Directory class for this purpose. This class cannot be instantiated and, instead, contains a number of static methods that can be used to work with any directory. We'll examine this class later in this section.
--------------------------------------------------------------------------------
After we've created an instance of the DirectoryInfo class, we can access its methods and properties. However, what if the user specified a directory that does not exist? Such a case would generate an unsightly runtime error. To compensate for this, we use a Try ... Catch block, nesting the calls to the DirectoryInfo classes properties and methods inside the Try block (lines 13 through 33). If the directory specified by the user doesn't exist, a DirectoryNotFoundException exception will be thrown. The Catch block starting on line 34 will then catch this exception and an error message will be displayed. Figure 2.8 shows the browser output when a user enters a nonexistent directory name.