国内最大的酷站演示中心!
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.