Common asp.net Code techniques (DPC&DWC Reference)--9

Source: Internet
Author: User
Tags array constructor eval file system html tags new features
asp.net Figure 2.8
An attractive error message is displayed if the user enters a invalid directory name.

A useful property of the DirectoryInfo class (and the FileInfo class, which we'll examine in the next section, "Reading, W Riting, and creating Files ") that deserves further attention are the Attributes property. This is type FileAttributes, a enumeration also found in the System.IO namespace. The FileAttributes enumeration lists various attributes a directory (or file) can have. Table 2.1 lists these attributes.

Table 2.1 Available Attributes in the FileAttributes enumeration
Attribute
Description

Archive
Indicates the file system entity ' s archive status

Compressed
Indicates the file system entity ' s compression status

Directory
Indicates if the file system entity is a directory

Encrypted
Indicates whether the file system entity is encrypted

Hidden
Indicates if the file system entity is hidden

Normal
If the file system entity has no attributes set, it is labeled as Normal

Notcontentindexed
Indicates whether the file system entity is indexed by the operating system ' s Indexing Service

Offline
Indicates if the file system entity is offline

ReadOnly
Indicates whether the file system entity is read-only

Reparsepoint
Indicates if the file system entity contains a reparse point (a block of user-defined data)

Sparsefile
Indicates if a file is defined as a sparse file

System
Indicates if the file is a system file

Temporary
Indicates whether the file system entity is temporary or not



Because each directory (or file) can have a number of attributes (such as a file being both hidden and a system file), the Single Attributes property has the capability of housing multiple pieces of information. To pick out of the individual attributes represented by the Attributes property, a bit-wise and (Bitand) can be used (Lin ES-through 61). To properly display the attributes for a directory in Listing 2.2.1, a helper function, Displayattributes, are called from Line, passing to it the FileAttributes enumeration returned by the Attributes property.


--------------------------------------------------------------------------------

Note

The bit-wise and operator, Bitand, is new to Visual Basic.NET. In previous versions of Visual Basic and VBScript, the and operator served both as a logical and bit-wise and. For a list of the new features in Visual Basic.NET check out Appendix A, "Breaking cahnges in Visual Basic.NET."


--------------------------------------------------------------------------------

The Displayattributes function, spanning lines through, returns a nicely formatted display listing the various Attri Butes indicated by the FileAttributes enumeration passed in (FSA). On lines through, a check are performed to determine if FSA contains a particular attribute; If it does, the textual description of the attribute is appended to Stroutput, which'll be returned by displayattributes At the end of the function.

The DirectoryInfo class contains two useful methods for retrieving a list of a directory ' s subdirectories and folders. These are two methods are GetDirectories (), which returns an array of DirectoryInfo, objects representing the subdirectories, a nd GetFiles (), which returns an array of FileInfo objects representing the list of files in the directory. (We'll examine the FileInfo object in detail on the next section, "Reading, writing, and creating Files." In lines to through, the array returned by the GetDirectories () method was iterated using a for each ... Next Loop, displaying the subdirectories for the directory represented by Dirinfo.

Listing 2.2.1 Demonstrates to list the properties of a directory (such as its attributes, creation date, last accessed Date, and, and retrieve the subdirectories for a given directory. However, we have not examined you to create and delete directories.

Recall that's DirectoryInfo class represents a specific directory (after all, the DirectoryInfo constructor requires a D Irectory path). Therefore, it makes sense the DirectoryInfo class can only is used to create subdirectories of the physical directory Represented by the DirectoryInfo instance. To create a subdirectory with the Createsubdirectory method:

Dim Dirinfo as DirectoryInfo = new DirectoryInfo ("C:\Inetpub\wwwroot\")

' Create a subdirectory
Dirinfo.createsubdirectory ("Images")
The preceding script creates an images subdirectory in the C:\Inetput\ directory. The following discusses the exceptions this createsubdirectory method can throw if something goes awry:

Argumentexception-this exception'll be thrown if your try to create a subdirectory that contains invalid directory Charac Ters (such as \,/,:, *,?, ",", ", and |).

Ioexception-this exception is thrown if your attempt to create a subdirectory that already.

Pathtoolongexception-this exception is thrown if the subdirectory your attempt to create contains too long a path. (at the time of writing this path length limitation is set at 248 characters.)

Securityexception-this exception occurs if the caller does not have sufficient.

To delete directory A, use the DirectoryInfo class ' s Delete method. The Delete method would delete the directory represented by the DirectoryInfo instance. The Delete method can accept a optional Boolean parameter recursedirs, which if True, would delete the directory, all of its Files, and all its subdirectories and their files. If Recursedir is False (or not specified in all) and your attempt to delete a directory this contains any files or Subdirec Tories, a IOException exception is thrown:

' Delete C:\ASP and All's subdirectories with the Delete method
Dim dirasp as New Directory ("C:\ASP")
Dirasp.delete (True)
While the createsubdirectory and delete methods of the DirectoryInfo class can is used to create or delete any directory O n the file system, it's a bit verbose if all you are want to does is quickly create new directory. The. NET Framework provides another class, Directory, which can use if you don't want to go through the trouble of CR Eating an instance of the DirectoryInfo class.

The Directory class contains a number of static methods (methods can be called without creating a new instance of the Directory Class). (In fact, your cannot create an instance of the Directory method-if your try you receive a "' System.IO.Directory.Direct Ory () ' is inaccessible due to it protection level ' error.) One of these static methods of the Directory class are createdirectory, which, as its name suggests, creates a directory! Simply use the following syntax:

Directory.CreateDirectory (DirectoryPath)
The CreateDirectory method would throw an IOException exception if the directory DirectoryPath already.
To delete directory A and the directory class, use the Delete method. The Delete method has two forms:

Directory.delete (DirectoryPath)
Directory.delete (DirectoryPath, Recursedirs)
The DirectoryPath is the path of this directory you want to delete. As with the DirectoryInfo class ' s Delete method, Recursedirs is a Boolean value, which if True, would delete the directory, All their files, and all their subdirectories and their files. If Recursedir is False (or not specified in all) and your attempt to delete a directory this contains any files or Subdirec Tories, an IOException exception would be thrown.


--------------------------------------------------------------------------------

Caution

When working with the file system using C #, keep in mind this string escape sequence for C # is the backslash (\). To insert a literal backslash into a string, your must use two consecutive backslashes. For example, to delete directory A, use Directory.delete ("c:\\asp");.


--------------------------------------------------------------------------------

Reading, writing, and creating Files
Because the. NET Framework provides a class for retrieving information about a particular directory (the DirectoryInfo CLA SS), it should come as no surprise that it also provides a class for accessing file information. This class, aptly named FileInfo, contains a number of properties similar to the DirectoryInfo class. For example, the Attributes, CreationTime, Exists, FullName, Lastaccessedtime, LastWriteTime, and Name properties are comm On to both the FileInfo and DirectoryInfo classes.

The methods of the FileInfo class are fairly straightforward; They provide the basic functionality for files. The methods to open a file are open, OpenRead, OpenText, and Openwrite. The methods to create a file are Create and CreateText. The methods to deletes and do miscellaneous file-related tasks are CopyTo, delete, and MoveTo.


--------------------------------------------------------------------------------

Note

The. NET Framework also includes a File class, which is strikingly similar to the Directory class. As with the DirectoryInfo and Directory classes, the FileInfo class allows for actions on a specific file while the file C Lass contains a number of static methods for use with the any generic file.


--------------------------------------------------------------------------------

Listing 2.2.2 illustrates how to read (and display) the contents of a-text file, as as-how-a-DataList and data Binding to display the contents's an array. A thorough examination of databinding and use of the DataList can is found in Chapter 7.

Listing 2.2.2 The FileInfo Class Can is Used to Retrieve Properties or the Contents of a File on the Web Server
1: <%@ Import namespace= "System.IO"%>
2: <script language= "VB" runat= "Server" >
3:sub Page_Load (sender as Object, E as EventArgs)
4:if not Page.IsPostBack Then
5: ' What directory are we interested in?
6:const Strdir = "C:\My projects\asp.net book\chapter 2\code\vb"
7:lblheader.text = "<b><u>file Listing for" & Strdir & ":</u></b>"
8:
9:dim Dirinfo as New DirectoryInfo (Strdir)
"Get the" files for the directory Strdir
11:dim Afiles as FileInfo () = Dirinfo.getfiles ("*.aspx")
12:dlfilelist.datasource = Afiles
13:dlfilelist.databind ()
14:end If
15:end Sub
16:
17:sub Dlfilelist_select (sender as Object, E as EventArgs)
18:dim strFilePath as String = _
19:dlfilelist.datakeys (DlFileList.SelectedItem.ItemIndex). ToString ()
20:dim objfile as FileInfo = new FileInfo (strFilePath)
21:dim objstream as StreamReader = Objfile.opentext ()
22:dim strContents as String = Objstream.readtoend ()
23:objstream.close ()
24:lblfilecontents.text = "<b>contents of" & Objfile.name & ":</b>" & _
: "<xmp>" & VbCrLf & strContents & vbCrLf & "</xmp>"
26:end Sub
: </script>
: : <body>
<form runat= "Server" >
<asp:label id= "Lblheader" runat= "Server"/><br>
<asp:datalist runat= "Server" id= "Dlfilelist"
33:onselectedindexchanged= "Dlfilelist_select"
34:datakeyfield= "FullName" >
<ItemTemplate>
: <li><%# DataBinder.Eval (Container.DataItem, "Name")%><br>
Panax Notoginseng: <font size=-1>
: [<asp:linkbutton text= "View Contents"
39:commandname= "Select" runat= "Server"/&GT;] |
: [<%# DataBinder.Eval (Container.DataItem, "Length")%> bytes]
: </font>
: <p>
: </ItemTemplate>
: </asp:DataList>
: <p><asp:label runat= "Server" id= "lblfilecontents"/>
: <form>
<body>
: The code in Listing 2.2.2 serves a very simple purpose:to list the asp.net pages on a particular directory and to allow T He user to view the source code for all one of these pages. This can is thought of as two separate tasks:

Listing the files in a particular directory

Displaying the contents of the selected file

The Page_Load event handler (lines 3 through) and the DataList control (lines through 4 4. The the Page_Load event handler checks to determine if the Page is being visited for the So, Page.IsPostBack would be False, and the code from lines 5 through would be executed). In such a case, we are want to display the files for a particular directory. On line 6, the directory path whose files is displayed has been hard coded and stored in the constant. By using concepts from Listing 2.2.1, however, Listing 2.2.2 is could to expanded the user to allow the directory.

Next, those files in the directory Strdir this end with the. aspx extension are returned (line 11). The GetFiles method of the DirectoryInfo class can accept a optional parameter indicating this only a subset of files Sho Uld is returned from the directory. This optional parameter, if specified, are a search criteria field in which wildcards can are used to limit the files Ed. Because we are only interested in listing asp.net pages, we want to grab only those files this have the. aspx extension. The GetFiles method returns a array of FileInfo objects, which we assign to our variable afiles (line 11).

On lines and I, we bind this array to dlfilelist, our DataList whose definition begins in line 36. The DataList uses databinding syntax to display the Name property of each FileInfo object in the Afiles array (line) Al Ong with the "Length" property, which indicates the file ' s size in bytes (line 40). In the DataList heading (lines through), the SelectedIndexChanged event was wired up to the Dlfilelist_select event H Andler; Furthermore, the DataList specifies the FullName property of the FileInfo class as it DataKeyField (line 34).

A LinkButton server control are created on lines and a-CommandName of Select. When this LinkButton is clicked, the page would be reposted and the Dlfilelist_select event handler'll be called. From the Dlfilelist_select event handler, the FullName of the file clicked can is programmatically determined because of T He DataKeyField property to line 34. If you are are unfamiliar with the DataList control and databinding, this might is a bit overwhelming to you. Don ' t worry, though; DataBinding is discussed thoroughly in Chapter 7.

After a View Contents link is clicked, the page would be reloaded and we ' re in to the second task:displaying the Contents of the selected file. This is handled the Dlfilelist_select event handler. On line, the clicked LinkButton ' s DataKeyField are extracted and stored in the variable strFilePath. This contains the "full path" to "file" we want to display.

Next, on line, a FileInfo object are instantiated and the constructor is called, passing it the path of the file we are Interested in. To simply read the contents of a-text file, the FileInfo class provides a OpenText method, which returns a StreamReader I Nstance that can is used to step through the contents of the file. On line, a StreamReader instance are created and assigned to the "object returned by" the OpenText method. Next, the entire stream is read to a string variable, strContents, and the stream is closed (line 23).

On line and the contents of the "selected" file are displayed in the Lblfilecontents label server control. Because we are displaying the contents of a file that likely contains HTML and Script-block code, the contents are Ded by a pair of XMP tags. (The XMP tag is a standard HTML tag, displays text ignoring all HTML tags.)

Figure 2.9 shows the output of the code in Listing 2.2.2 when we the page. Note this contents of the specified directory are displayed with a link to view the source and a note on their file Si Ze.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.