Using the My object, you can write some text to a file via a single statement. The WriteAllText method accepts as arguments a path and the string to be written to the file (as well as a third optional argument that determines whether the text will be appended to the file or will replace the current contents), writes some text to the file (the contents of a TextBox control in the following sample), and then closes the file:
My.Computer.FileSystem.WriteAllText(fName, TextBox1.Text, True)
Code language: CSS (css)
If the specified file does not exist, the write method creates it. To write binary data to a file, use the WriteAllBytes method, whose syntax is almost identical, but the second argument is an array of bytes instead of a string.
By the way, because My is not a class, you can’t import it to a file and shorten the statements that access its members; you have to fully qualify the member names. You can still use the With statement, as shown here:
With My.Computer.FileSystem
.WriteAllText(fname, TextBox1.Text, True)
End With
Code language: CSS (css)
To read back the data saved with the WriteAllText and WriteAllBytes methods, use the ReadAllText and ReadAllBytes methods, respectively. The ReadAllText method accepts as an argument the path of a file and returns its contents as a string. ReadAllBytes accepts the same argument, but returns the file’s contents as an array of bytes. This is all you need to know in order to save data to disk files between sessions with the My object. The following code segment saves the contents of the TextBox1 control to a user-specified file, clears the control, reads the text from the same file, and populates the TextBox1 control:
' Set up the SaveFileDialog control
SaveFileDialog1.DefaultExt = "*.txt"
SaveFileDialog1.AddExtension = True
SaveFileDialog1.FileName = ""
SaveFileDialog1.Filter = "Text Files|*.txt|All Files|*.*"
If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
' Use the WriteAllText method to save the text
My.Computer.FileSystem.WriteAllText( _
SaveFileDialog1.FileName, TextBox1.Text, False)
End If
' Clear the control
TextBox1.Clear()
' Set up the OpenFileDialog control
OpenFileDialog1.DefaultExt = "txt"
OpenFileDialog1.Filter = "Text Files|*.txt|All Files|*.*"
OpenFileDialog1.FileName = "Test File.txt"
If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
' Use the ReadAllText method to read back the text
' and display it on the TextBox control
TextBox1.Text = My.Computer.FileSystem.ReadAllText( _
OpenFileDialog1.FileName)
End If
Code language: PHP (php)
As you can see, it takes two statements to send the data to the file and read it back. All other statements set up the Open and Save As dialog boxes.
Here’s another example of using the FileSystem object. To delete a folder, call the DeleteDirectory method of the My.Computer.FileSystem component, which accepts three arguments: the name of the folder to be deleted, a constant that specifies whether the DeleteDirectory method should delete the contents of the specified folder if the folder isn’t empty, and another constant that determines whether the folder will be deleted permanently or moved to the Recycle Bin. This constant is a member of the FileIO.RecycleOption enumeration: DeletePermanently (to remove the file permanently from the file system) and SendToRecycleBin (moves the file to the Recycle Bin). To delete a file, use the DeleteFile method, which has the same syntax. (The first argument is the path of a file, not a folder.)
Another interesting member of the FileSystem object is the SpecialDirectories property, which allows you to access the special folders on the target computer (folders such as My Documents, the Desktop, the Program Files folder, and so on). Just enter the name of the SpecialDirectories property followed by a period to see the names of the special folders in the IntelliSense box. To find out the application’s current folder, call the CurrentDirectory method. The RenameDirectory and RenameFile methods allow you to rename folders and files, respectively. Both methods accept as arguments the original folder name or filename and the new name, and perform the operation. They do not return a value to indicate whether the operation was successful, but they throw an exception if the operation fails.
The CopyFile and CopyDirectory methods copy a single file and an entire folder, respectively. They accept as arguments the path of the file or folder to be copied, the destination path, and an argument that determines which dialog boxes will be displayed during the copying operation. The value of this argument is a member of the FileIO.UIOption enumeration: AllDialogs (shows the progress dialog box and any error dialog boxes) and OnlyErrorDialogs (shows only error dialog boxes). The following code segment copies a fairly large folder. It’s interesting to see how it displays the usual file copy animation and prompts users every time it can’t copy a folder (because the user doesn’t have adequate privileges or because a file is locked, and so on).
Dim dir as String
dir = "C:\Program Files\Microsoft Visual Studio 9.0"
Try
My.Computer.FileSystem.CopyDirectory( _
dir, "E:\Copy of " & _
My.Computer.FileSystem.GetName(dir), _
Microsoft.VisualBasic.FileIO. _
UIOption.AllDialogs, _
FileIO.UICancelOption.ThrowException)
Catch ex As Exception
MsgBox(ex.Message)
End Try
Code language: PHP (php)
Please do change the destination drive (E: in the preceding sample code segment); you may not have an E: drive, or you may overwrite a working installation of Visual Studio 2008. Notice that I used the GetName method of the FileSystem component to extract the last part of the path and then combine it with the new drive name. The last argument of the CopyDirectory method, which is a member of the UICancelOption enumeration: DoNothing or ThrowException, determines how the method reacts when the user clicks the Cancel button on the copy animation. I used the ThrowException member and embedded the entire statement in an exception handler. If you click the Cancel button while the folder’s files are being copied, the following message will appear:
The operation was canceled.
Cancelling a copy operation doesn’t reset the destination folder. You must insert some additional code to remove the files that have been copied to the destination folder, or notify the user that some files have copied already and they’re not automatically removed.
To manipulate folders, use the CreateDirectory and DirectoryExists methods, which accept as an argument the path of a folder. To find out whether a specific file exists, call the FileExists method, passing the file’s path as the argument.
To retrieve information about drives, folders, and files, use the GetDriveInfo, GetDirectoryInfo, and GetFileInfo methods, respectively. These methods accept as an argument the name of the drive or the path to a folder/file, respectively, and return the relevant information as an object. Drive properties are described with the IO.DriveInfo class, folder properties are described with the IO.DirectoryInfo class, and file properties with the IO.FileInfo class. These objects are part of the Framework’s IO namespace and they provide properties such as a directory’s path and attributes, a file’s path, size, creation and last modification date, and so on. The three objects are described in detail later in this chapter, in the discussion of the IO namespace. To find out the properties of the C: drive on your system, execute a statement such as the following:
Dim DI As IO.DriveInfo = _
My.Computer.FileSystem.GetDriveInfo("C")
Debug.WriteLine("DRIVE " & DI.Name & vbCrLf & _
"VOLUME " & DI.VolumeLabel & vbCrLf & _
"TYPE " & DI.DriveType.ToString & vbCrLf & _
"TOTAL SIZE " & DI.TotalSize.ToString & vbCrLf & _
"FREE SPACE " & DI.AvailableFreeSpace.ToString)
Code language: PHP (php)
This statement produced the following output on my system:
DRIVE C:\
VOLUME VAIO
TYPE Fixed
TOTAL SIZE 3100019372032
FREE SPACE 50142416896
To retrieve information about all drives in your system, call the Drives method, which returns a read-only collection of DriveInfo objects. If you want to search a folder for specific files, use the FindInFiles method, which is quite flexible. The FindInFiles method goes through all files in a specified folder and selects files by a wildcard specification, or by a string in their contents. The method has two overloaded forms; their syntax is the following:
FindInFiles(dir, containsText, ignoreCase, FileIO.SearchOption)
Code language: CSS (css)
and
FindInFiles(dir, containsText, ignoreCase, _
FileIO.SearchOption,fileWildCards() String)
Code language: JavaScript (javascript)
Both methods return the list of matching files as a read-only collection of strings. The dir argument is the folder to be searched, and the containsText argument is the string we want to locate in the files. The ignoreCase argument is a True/False value that determines whether the search is case-sensitive, and the SearchOption argument is a member of the FileIO.SearchOption enumeration and specifies whether the method will search in the specified folder or will include the subfolders as well: SearchAllSubdirectories, SearchTopLevelOnly. The second overloaded form of the method accepts an additional argument, which is an array of strings with the patterns to be matched (for example, *.txt, Sales*.doc, *.xls, and so on). The following statements locate all text, .doc, and .xml files in the Program Files folder that contain the string Visual Basic. The search is case-insensitive and includes the all subfolders under Program Files.
Dim patterns() As String = {"*.txt", "*.doc", "*.xml"}
Dim foundFiles As System.Collections.ObjectModel. _
ReadOnlyCollection(Of String)
foundFiles = My.Computer.FileSystem.FindInFiles( _
"C:\Program Files", "visual basic", True, _
FileIO.SearchOption.SearchAllSubDirectories, patterns)
Dim file As String
For Each file In foundFiles
Debug.WriteLine(file)
Next
Code language: PHP (php)
A Simpler Method of Saving Data to Files
The Framework provides an attractive alternative to writing data to files: the serialization mechanism. You can create collections of objects and persist them to a file via a few simple statements. Actually, it’s much simpler to create a collection of customer/product/sales data and persist it as a whole, than to write code to write every field to a file (let’s not forget the code for reading the data back into the application). Serialization is a major component of .NET, and it’s discussed in detail in Chapter, “XML and Object Serialization.”
This concludes the overview of the file-related methods of the FileSystem component. This component doesn’t expose many members, and their syntax is quite simple. You can experiment with the methods and properties of the FileSystem component to get a better idea of the type of operations you can perform with it. In the remainder of this chapter, you’ll find a detailed discussion of the IO namespace.