File Management with the My Namespace


The My namespace includes several file management features in its My.Computer.FileSystem branch, including features that create streams for reading and writing.

My Namespace Versus Visual Basic Commands

Most of the My.Computer.FileSystem object's members exist to replace or supplement file management features already present in Visual Basic. Table 15-2 lists some of the long-standing file and directory interaction features in Visual Basic, and their equivalents in My.Computer.FileSystem.

Table 15-2. Two Ways of Doing the Same Thing

Visual Basic Feature

Purpose

My.Computer.FileSystem Equivalent

ChDir

Change the current "working" directory on a specified or default drive.

The FileSystem.CurrentDirectory property gets and sets the current "working" directory as understood by the application. You set the active directory through an absolute or relative path string.

ChDrive

Change the current "working" drive.

The FileSystem.CurrentDirectory property not only reports or changes the active directory; it also modifies the active drive.

CurDir

Identify the current "working" directory and drive as a full path string.

Once again, FileSystem.CurrentDirectory is the substitute for this Visual Basic directory feature. CurDir does have a little more flexibility; it allows you to determine the current directory on a drive other than the current drive. This can't be done with FileSystem.CurrentDirectory.

Dir

Retrieve files and directories in a parent directory that match a specific name pattern.

The FileSystem.GetDirectories and FileSystem.GetFiles methods both support wildcard patterns when retrieving matching directory and file names. Dir requires that you call it once for each entry to return, and it doesn't work well when processing nested directories. The FileSystem equivalents return collections of matching items, and can optionally descend the entire subdirectory tree of a base path.

FileCopy

Make a copy of a file.

The FileSystem.CopyFile provides a few additional user-friendly features beyond FileCopy. But what's the deal with the reversal of "File" and "Copy?"

FileDateTime

Retrieve the creation or modification date and time of a file.

Use the FileSystem.GetFileInfo method to retrieve a FileInfo object replete with details about a file. You'll probably focus on the FileInfo.LastWriteTime property, but you can also get the original creation time and the last access time, features not available through the lowly and now disgraced FileDateTime function.

FileLen

Retrieve the length, in bytes, of a file.

Obtain a FileInfo object through the FileSystem.GetFileInfo method, and access that object's Length property to get the file size in bytes.

GetAttr

Retrieve the attributes of a file as a bit field.

Get details on a file through the FileSystem.GetFileInfo method, and use the returned FileInfo object's Attributes property to examine your attribute of choice. This object also exposes an IsReadOnly Boolean value.

Kill

Delete a file or empty directory.

The FileSystem.DeleteFile and FileSystem.DeleteDirectory methods replace the Kill procedure, and provide additional options not available with Kill. Plus, you won't have the police knocking at your door asking why you constantly type Kill, Kill, Kill.

MkDir

Create a new directory.

The FileSystem.CreateDirectory method is a gentle replacement for MkDir. Anyway, "mkdir" is an old UNIX command, and you're not programming on UNIX, are you?

Rename

Change the name of a file or directory.

Rename is replaced by distinct FileSystem.RenameFile and FileSystem.RenameDirectory methods.

RmDir

Delete a directory, even if it contains files.

The FileSystem.DeleteDirectory deletes directories that still contain other files, an action that RmDir rejected. There's also an option to send the files to the Recycle Bin.

SetAttr

Modify the attributes of a file using a bit field.

Same process listed for GetAttr previously. The FileInfo object's Attributes and IsReadOnly properties are read/write values, assuming you have the necessary security rights to change attributes.


Why would Microsoft introduce so many new My features that duplicate existing Visual Basic features? Perhaps it's a way to bring consistency to file-based programming practices through a more object-oriented approach. Or maybe it's yet another move by Microsoft, the United States government, the Knights Templar, Burger King, and other groups set on world domination by controlling you, your family, and your community through the "hidden hand" of extra-long source code statements.

Reading and Writing Files Through My

The My.Computer.FileSystem.OpenTextFileReader and parallel OpenTextFileWriter methods provide shortcuts to the filename-based constructor for StreamReader and StreamWriter objects. This statement:

Dim inputStream As IO.StreamReader = _    My.Computer.FileSystem.OpenTextFileReader( _    fileNamePath) 


is identical to:

Dim inputStream As New IO.StreamReader(fileNamePath) 


For me, the second version is better due to its terse nature, but it's between you and your source code review team as to which one you will use.

If you want to load the entire contents of a file into either a String or a Byte array, there's no need to open a stream now that My includes the My.Computer.FileSystem.ReadAllText and related ReadAllBytes methods. This statement dumps the entire content of a file into a String.

Dim wholeFile As String = _    My.Computer.FileSystem.ReadAllText( _    fileNamePath) 


The My.Computer.FileSystem.WriteAllText and WriteAllBytes methods do the same thing, but in the opposite direction. There's an append Boolean argument that lets you either append or replace the new content relative to any existing content in the file.

My.Computer.FileSystem.WriteAllText( _    fileNamePath, dataToWrite, True)  ' True=append 


One feature that has always been missing from Visual Basic is the ability to conveniently scan a delimited file (such as tab-delimited or comma-delimited) or a fixed-width-field file, and extract the fields on each line without a lot of extra parsing code. Visual Basic now includes the Microsoft.VisualBasic.FileIO.TextFieldParser object that simplifies this process. This object lets you indicate either a field delimiter (such as the tab character) or an array of column sizes. Once you associate it with a file path, it reads each data line, breaking up the distinct fields for you into a string array. The My.Computer.FileSystem.OpenTextFieldParser method opens the file and defines the parsing method in one fell swoop.

Dim dataFields() As String Dim sourceFile As FileIO.TextFieldParser ' ----- Open the file with tab-delimited fields. sourceFile = My.Computer.FileSystem.OpenTextFieldParser( _    sourceFilePath, vbTab) ' ----- Process each line. Do While Not sourceFile.EndOfData    dataFields = sourceFile.ReadFields()    ' ----- dataFields is a simple string array,    '       so you can examine each field directly.    If (dataFields(0) = "NEW") Then    ' ----- and so on... Loop sourceFile.Close() 


The TextFieldParser can also detect comment lines and ignore them silently. I am sure that it's using a StreamReader secretly hidden inside the object's black box. While the internals are hidden from view, the exposed features of this object make it a snap to process field-based text files.




Start-to-Finish Visual Basic 2005. Learn Visual Basic 2005 as You Design and Develop a Complete Application
Start-to-Finish Visual Basic 2005: Learn Visual Basic 2005 as You Design and Develop a Complete Application
ISBN: 0321398009
EAN: 2147483647
Year: 2006
Pages: 247
Authors: Tim Patrick

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net