Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
(ebook) Visual Studio .NET Mastering Visual Basic.pdf
Скачиваний:
120
Добавлен:
17.08.2013
Размер:
15.38 Mб
Скачать

584 Chapter 13 WORKING WITH FOLDERS AND FILES

The syntax of the OpenRead method is:

FStream = fileObj.OpenRead(path)

where fileObj is a properly initialized File variable. The OpenRead method is equivalent to opening an existing file with read-only access with the Open method.

OpenText

This method opens an existing text file for reading and returns a StreamReader object associated with this file. Its syntax is

FStream = File.OpenText(path)

Why do we need an OpenText method in addition to the Open, OpenRead, and OpenWrite methods? The answer is that text can be stored in different formats. It can be plain text (UTF-8 encoding), ASCII text, or Unicode text. The StreamReader object associated with the text file will perform the necessary conversions, and you will always read the correct text from the file. The default encoding for the OpenText method is UTF-8.

OpenWrite

This method opens an existing file in write mode and returns a StreamWriter object associated with this file. You can use this stream to write to the file, as you will see later in this chapter.

The syntax of the OpenRead method is:

FStream = File.OpenWrite(path)

where path is the path of the file.

This ends our discussion of the Directory and File objects, which are the two major objects for manipulating files and folders. In the following section, I will present the DirectoryInfo and FileInfo classes briefly, and then we’ll build an application that puts together much of the information presented so far.

The DirectoryInfo Class

The DirectoryInfo and FileInfo classes are similar to the Directory and File classes, but they must be instantiated before they are used. Their constructors specify the folder or file they will act upon, and you don’t have to specify a folder or file when you call their methods.

To create a new instance of the DirectoryInfo class that references a specific folder, supply the folder’s path in the class’s constructor:

Dim DI As New DirectoryInfo(path)

Methods

The members of the DirectoryInfo class are equivalent to the members of the Directory class, and you will recognize them as soon as you see them in the IntelliSense drop-down list. Here are a couple of methods that are unique to the DirectoryInfo class.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

ACCESSING FOLDERS AND FILES 585

CreateSubdirectory

This method creates a subfolder under the folder specified by the current instance of the class, and its syntax is

CreateSubdirectory(path)

The CreateSubdirectory method returns a DirectoryInfo object that represents the new subfolder. The path argument need not be a single folder’s name. If you specified multiple nested folders, the CreateSubdirectory method will create the appropriate hierarchy, similar to the CreateDirectory method of the Directory class.

GetFileSystemInfos

This method returns an array of FileSystemInfo objects, one for each item in the folder referenced by the current instance of the class. The items can be either folders or files. To retrieve information about all the entries in a folder, create an instance of the DirectoryInfo class and then call its GetFileSystemInfos method:

Dim DI As New DirectoryInfo(path) Dim itemsInfo() As FileSystemInfo itemsInfo = DI.GetFileSystemInfos()

You can also specify an optional search pattern as argument when you call this method:

itemsInfo = DI.GetFileSystemInfos(pattern)

The FileSystemInfo objects expose a few properties, which are not new to you. The Name, FullName, and Extension return a file’s or folder’s name or full path or a file’s extension. The CreationTime, LastAccessTime, and LastWriteTime are also properties of the FileSystemInfo object, as well as the Attributes property.

You will notice that there are no properties that determine whether the current item is a folder or a file. To find out the type of an item, use the Directory member of the Attributes property:

If itemsInfo(i).Attributes And FileAttributes.Directory Then

{current item is a folder }

Else

{current item is a file } End If

The code in Listing 13.7 retrieves all the items in the C:\Program Files folder and prints their name along with the FOLDER and FILE characterization.

Listing 13.7: Processing a Folder’s Items with the FileSystemInfo Object

Dim path As String = “C:\Program Files” Dim DI As New DirectoryInfo(path)

Dim itemsInfo() As FileSystemInfo itemsInfo = DI.GetFileSystemInfos() Dim item As FileSystemInfo

For Each item In itemsInfo

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

586 Chapter 13 WORKING WITH FOLDERS AND FILES

If item.Attributes And FileAttributes.Directory Then

Console.Write(“FOLDER “)

Else

Console.Write(“FILE “)

End If

Console.WriteLine(item.Name)

Next

Notice the similarities and differences between the GetFileSystemInfos method of the DirectoryInfo class and the GetFileSystemEntries of the Directory object. GetFileSystemInfos returns an array of objects that contains information about the current item (file or folder). GetFileSystemEntries returns an array of strings (the names of the folders and files).

The FileInfo Class

The FileInfo class exposes many properties and methods, which are equivalent to the members of the File class, so I’m not going to repeat all of them here. The Copy/Delete/Move methods allow you to manipulate the file represented by the current instance of the FileInfo class, similar to the methods by the same name of the File class. Although there’s substantial overlap between the members of the FileInfo and File classes, the difference is that with FileInfo you don’t have to specify a path. Its members act on the file represented by the current instance of the FileInfo class.

Properties

The FileInfo object exposes a few rather trivial properties, which are mentioned briefly here.

Length

This property returns the size of the file represented by the FileInfo object in bytes. The File class doesn’t provide an equivalent property or method.

CreationTime, LastAccessTime, LastWriteTime

These properties return a date value which is the date on which the file was created, accessed for the last time, or written to for the last time. They are equivalent to the methods of the File object by the same name and the “Get” prefix.

Name, FullName, Extension

These properties return the filename, full path, and extension of the file represented by the current instance of the FileInfo class. They have no equivalents in the File class, because the File class’s methods require that you specify the path of the file, so its path and extension are known.

Methods

The FileInfo object exposes methods for manipulating files, and most of them are equivalent to the methods of the File object.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

ACCESSING FOLDERS AND FILES 587

CopyTo, MoveTo

These two methods copy and move the file represented by the current instance of the FileInfo class. Both methods accept a single argument, which is the destination of the operation (the path to which the file will be copied or moved). If the destination file exists already, you can overwrite it by specifying a second optional argument, which has a True/False value:

FileInfo.CopyTo(path, force)

Both methods return an instance of the FileInfo class, which represents the new file—if the operation completed successfully.

Directory

This method returns a DirectoryInfo value that contains information about the file’s parent directory.

DirectoryName

This method returns a string with the file’s parent directory’s name. The following statements return the two (identical) strings shown in bold:

Dim FI As FileInfo

FI = New FileInfo(“c:\folder1\folder2\folder3\test.txt”) Console.WriteLine(FI.Directory().FullName) c:\folder1\folder2\folder3

Console.WriteLine(FI.DirectoryName())

c:\folder1\folder2\folder3

Of course, the Directory method returns an object, which you can use to retrieve other properties of the parent folder.

The Path Class

The Path class contains an interesting collection of methods, which you can think of as utilities. The Path class’s methods perform simple tasks such as retrieving a file’s name and extension, returning the full path description of a relative path, and so on. The Path class’s members require that you specify the path on which they will act. In other words, there’s no constructor for the Path class that would allow you instantiate a Path object to represent a specific path.

Properties

The Path class exposes the following properties. Notice that none of these members apply to a specific path; they’re general properties that return settings of the operating system.

AltDirectorySeparatorChar

This property returns an alternate directory separator character. For Windows 2000, the AltDirectorySeparatorChar property returns the slash character (/).

DirectorySeparatorChar

This property returns the directory separator character. For Windows 2000, the DirectorySeparatorChar returns the backslash character (\).

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

588 Chapter 13 WORKING WITH FOLDERS AND FILES

InvalidPathChars

This property returns the list of invalid characters in a path as an array of characters. The following statements print the invalid path characters to the Output window; their output is shown in bold below the code:

Dim p As Path

Dim invalidPathChars() As Char invalidPathChars = p.InvalidPathChars Dim c As Char

For Each c In invalidPathChars Console.Write(c & vbtab)

Next

/ \ “ < > |

You can use these characters to validate user input, or pathnames read from a file. If you have a choice, let the user select the files through the Open dialog box, so that their pathnames will always be valid.

PathSeparator

This property returns separator character that may appear between multiple paths. For Windows 2000, this character is the semicolon (;).

VolumeSeparatorChar

This property returns the volume separator character. For Windows 2000, this character is the colon (:).

Methods

The most useful methods exposed by the Path class are like utilities for manipulating file and pathnames, and they described in the following sections. Notice that the methods of the Path class are shared: you must specify the path on which they will act.

ChangeExtension

This method changes the extension of a file, and its syntax is

newExtension = Path.ChangeExtension(path, extension)

The return value is the new extension of the file (a string value). The first argument is the file’s path, and the second argument is the file’s new extension. If you want to remove the file’s extension, set the second argument to Nothing. The following statement changes the extension of the specified file from “BIN” to “DAT”:

Dim path As String = “c:\My Documents\NewSales.bin”

Dim newExt As String = “.dat”

Path.ChangeExtension(path, newExt)

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

ACCESSING FOLDERS AND FILES 589

Combine

This method combines two path specifications into one, and its syntax is

newPath = Path.Combine(path1, path2)

Use this method to combine a folder path with a file path. The following expression will return the string shown in bold:

Path.Combine(“c:\textFiles”, “test.txt”) c:\textFiles\test.txt

Notice that the Combine method inserted the separator, as needed. It’s a simple operation, but if you had to code it yourself, you’d have to examine each path and determine whether a separator must be inserted.

GetDirectoryName

This method returns the directory name of a path. The statement

Path.GetDirectoryName(“C:\folder1\folder2\folder3\Test.txt”)

will return the string

C:\folder1\folder2\folder3

GetFileName, GetFileNameWithoutExtension

These two methods return the filename in a path, with and without its extension, respectively.

GetFullPath

This method returns the full path of the specified path; you can use it to convert relative pathnames to fully qualified pathnames. The following statement returned the string shown in bold on my computer (it will be quite different on your computer, depending on the current directory):

Console.WriteLine(Path.GetFullPath(“..\..\Test.txt”))

C:\Mastering VB.NET\Chapters\Chapter 13\Projects\Test.txt

The pathname passed to the method as argument need not exist. The GetFullPath method will return the fully qualified pathname of a nonexisting file, as long as the path doesn’t contain invalid characters.

GetTempFile, GetTempPath

The GetTempFile method returns a unique filename, which you can use as temporary storage area from within your application. The name of temporary file can be anything, since no user will ever access it. In addition, the GetTempFile method creates a zero-length file on the disk, which you can open with the Open method. A typical temporary filename is the following:

C:\DOCUME~1\TOOLKI~1\LOCALS~1\Temp\tmp105.tmp

which was returned by the following statement on my system:

Console.WriteLine(File.GetTempFile)

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com