Using the File and StreamWriter Classes in the .NET Framework

Using the File and StreamWriter Classes in the .NET Framework

When you want to use the File class in your programs, import System.IO and add a reference to the assembly (if it's not automatically added for you). As we saw earlier, the static File class has an AppendText method that returns a StreamWriter object that handles all the heavy lifting of reading and writing.

public static System.IO.StreamWriter AppendText(string path);

How do we actually use the AppendText method of the File class? In the following code example, we first dimension a string variable, sFileName, that will hold the name and location of the file we are interested in. Next we dimension a variable, fStreamWriter, as type StreamWriter and assign it the return value of the AppendText method of the File class. The AppendText method creates a StreamWriter object that appends text to a file on the specified path or creates the file if it does not already exist.

Dim sFileName As String = "C:\Text.txt" Dim fStreamWriter As StreamWriter = File.AppendText(sFileName) With fStreamWriter .WriteLine("This is the first line of our file.") .WriteLine("The second line of important information.") .Flush() .Close() End With

Pretty simple, eh? Because both the StreamWriter and File classes are static, we don't declare new instances of either. We use them as-is and use the WriteLine method of the StreamWriter object to write some text to the file. Technically, our example doesn't need to call the Flush method because the Close method calls Flush for us. It's better not to rely on the default behavior of the language, however. As a personal preference, I explicitly flush any file contents and then close the file.

Our simple example created a text file and wrote the strings to that file. We can easily see this file in Notepad, as shown in Figure 5-4.

Figure 5-4

The output from our simple example.

Reading Our File

Now that we've created and written information to our Text.txt file and closed it, let's see how to read information from it. To open a file, you need to manipulate the same System.IO objects. The File class has a number of different methods for opening files, but for this example we will use the OpenText method. This particular method returns a StreamReader object, which is ideal for reading lines of information from a standard text file.

public static System.IO.StreamReader OpenText(string path);

Once again, by simply looking at the signatures of the File class methods, we can see exactly how to implement code that reads from a text file. The following code demonstrates using the OpenText method, passing it the name of the file you intend to open. You should always include a fully qualified path when specifying the file.

Dim fStreamReader As StreamReader = File.OpenText(sFileName) Dim sFileContents As String sFileContents = fStreamReader.ReadToEnd fStreamReader.Close() MessageBox.Show(sFileContents)

Here we declare a variable of type StreamReader and set it to an open file. Then, using the ReadToEnd method of the StreamReader object, we assign the file contents to a string variable, sFileContents. Because we are not writing to the file, we don't need to explicitly flush its contents. In this example, we simply declare the StreamReader on one line and read the entire contents of the file in another line. Two lines of code to read a file—pretty powerful. We then display the file's contents in a message box, as shown in Figure 5-5.

Figure 5-5

The contents of our file.

If you want a better sense of exactly how the File and StreamReader classes interact, you can dimension the fStreamReader in this manner:

Dim fStreamReader As New StreamReader( _ File.Open(sFileName, FileMode.OpenOrCreate))

You can see that you must first open a file and pass it as a parameter to the StreamReader. Again, pretty simple coding.

Now take a look at the second and third methods of the File class, the overloaded Copy methods. The first method simply copies a source file to a destination file, and the second overloaded method permits us to pass a Boolean value to indicate whether we want to overwrite the destination file if it exists. Because the return type is void (C# terminology for nothing returned), we simply invoke the method. (It might be nice if the method returned an enumerated constant that indicates whether the copy was successful, but there are other ways to check for success, as we will see in a moment.)

public static void Copy(string sourceFileName, string destFileName); public static void Copy(string sourceFileName, string destFileName, bool overwrite);

The Copy method is even easier to use than the AppendText and ReadToEnd methods we just looked at. We simply pass in the name of a valid source file and the name and location of where we want it copied—one line of code.

Dim sSource As String = "C:\Text.txt" Dim sDestination As String = "C:\Copy.txt" File.Copy(sSource, sDestination, True)

In your production code, you would certainly check to see whether the copy operation was successful. As with most .NET classes, we can perform this check with one line of code. The File.Exists method takes the name and location of a file and determines whether it exists. You can see that this method returns a Boolean True or False.

public static bool Exists(string path);

As long as we have imported System.IO into our code, we can simply use the static File object's Exists method.

If File.Exists(sDestination) Then 'Do important things End If

The FileInfo Class

Because the File class is static, we can't use it in every case. We will usually need a class that works with specific instances of a file, which is where the FileInfo class comes in handy. For example, we might want to verify that the file we copied contains more than zero bytes. (While the file might be copied, it's very possible that the file's contents weren't copied. The file might exist, but it could be empty. In production code, for example, if we copied a file and there was not enough disk space or a problem writing to disk, we would need to know that and certainly check for it.)

Unlike the static File class, the FileInfo class permits us to create new instances for individual files. The FileInfo class contains most of the same methods of the File class for general-purpose uses and also lets us create separate objects for each individual file. Think of the File class as a utility class and the FileInfo class as the class to use to manipulate specific files. We want to use the FileInfo class because it contains all instance methods and can actually perform more tasks than the File class. The static methods of the File class perform security checks on all methods, so if you are going to reuse an object several times, use the FileInfo class instead if the security checks are not necessary.

The FileInfo class provides instance methods for the creation, copying, deletion, moving, and opening of files and aids in the creation of FileStream objects. Use WinCV to find the FileInfo class, as shown in Figure 5-6. You can see that the class includes a constructor, so we can create individual FileInfo objects for our files. Notice that FileInfo has methods that accomplish the same tasks as the methods in the File class.

Figure 5-6

The FileInfo class in WinCV.

The following code shows how to use the FileInfo class to get information about a file.

Dim sFileName As String = "C:\Text.txt" Dim sFileData As String Dim fInfo As FileInfo = New FileInfo(sFileName) With fInfo sFileData += "Creation Time: " & _ .CreationTime.ToLongTimeString CtrlChrs.CrLf sFileData += "File Directory: " & _ .Directory.ToString CtrlChrs.CrLf sFileData += "Full Name: " & .FullName & CtrlChrs.CrLf sFileData += "File Size (bytes): " & _ .Length.ToString CrlChrs.CrLf End With MessageBox.Show(sFileData, "FileInfo Methods", _ MessageBoxButtons.OK, MessageBoxIcon.Information)

Figure 5-7 displays the message box that contains information about the file we created earlier.

Figure 5-7

You can use the FileInfo class to retrieve information about a file.

The return type of the CreationTime property must be assigned to a variable of type DateTime. This situation is where the strong typing of .NET helps us get away from the nasty run-time errors that result from late binding. The common language runtime knows exactly what data type to expect ahead of time. If we inadvertently try to assign the return value of the CreationTime property to a string, the compiler will bark at us during design time, not when the user is running our application.

You can see the benefits of using the FileInfo class. Not only can we do the same tasks with it as with the File class, but also FileInfo contains many properties that permit us to retrieve all sorts of useful information about the file in question.

Creating a New File

Of course, we can also easily create a new file and write to it. The first thing we do is create a new instance of the FileInfo class with a string containing the name and location of the file we'd like to create. The following code fragment demonstrates how to use the FileInfo class to create and write to a file.

Dim sFileName As String = "C:\FileInfo.txt" Dim fInfo As FileInfo = New FileInfo(sFileName) Dim fStreamWriter As StreamWriter = fInfo.AppendText fStreamWriter.WriteLine("Using the FileInfo Class")

We create a new instance of the FileInfo class, which is held in the fInfo variable. Then we use the AppendText method of fInfo, which returns a StreamWriter object. That object is held in our variable fStreamWriter. Then, using fStreamWriter, we can simply use the WriteLine method to write to the file.

Enumerating Directory Entries Using the Framework

The ability to enumerate the files and subdirectories of a directory is essential for many programming tasks. The .NET FileInfo and DirectoryInfo classes make this task easy. Why not use the File and Directory classes? Because we usually want to retrieve information such as the size and creation date for a given file. The File class focuses on the use of noninstantiated methods, while the FileInfo class offers methods based on an instance of a FileInfo object. The Directory and DirectoryInfo classes are similar.

By looking at the signatures of the various properties of the DirectoryInfo class, you can easily see whether you can read (get) a property or write (set) that property.

// Properties public FileAttributes Attributes { get; set; } public DateTime CreationTime { get; set; } public bool Exists { virtual get; } public string Extension { get; } public string FullName { virtual get; } public DateTime LastAccessTime { get; set; } public DateTime LastWriteTime { get; set; } public string Name { virtual get; } public DirectoryInfo Parent { get; } public DirectoryInfo Root { get; }

To be sure we understand how to use the properties, let's look at the Attributes property as an example. You can see that we can both read and write to the Attributes property. It also returns a value of type FileAttributes. Therefore, we must declare a variable of type FileAttributes to hold the object returned from the Attributes property. See the pattern? We declare a variable that corresponds to the return type of the property. Once you understand that, you can use any class in the .NET Framework. The following code fragment demonstrates the basics of using the DirectoryInfo class to get information about a file.

Dim sFileName As String = "C:\Text.txt" 'First create a new instance of a DirectoryInfo object Dim diDirectoryInfo As DirectoryInfo = _ New DirectoryInfo(sFileName) 'Now that we have the DirectoryInfo object, call its ' Attributes property and assign it to a variable of ' type FileAttributes. Dim diAttributes As FileAttributes = _ diDirectoryInfo.Attributes Dim sFileInformation As String sFileInformation += "File Name: " & sFileName & _ CtrlChrs.CrLf If diAttributes = FileAttributes.Normal Then sFileInformation += "The file is normal" & CtrlChrs.CrLf End If If diAttributes = FileAttributes.Archive Then sFileInformation += "The file is not archived" & CtrlChrs.CrLf End If If diAttributes = FileAttributes.Hidden Then sFileInformation += "The file is hidden" & CtrlChrs.CrLf Else sFileInformation += "The file is not hidden" & CtrlChrs.CrLf End If If diAttributes = FileAttributes.Directory Then sFileInformation += "The entry is a directory" & _ CtrlChrs.CrLf Else sFileInformation += "The entry is a file" & CtrlChrs.CrLf End If MessageBox.Show(sFileInformation, _ "DirectoryInfo Properties", MessageBoxButtons.OK, _ MessageBoxIcon.Information)

It's also easy to use the Attributes property to change a file's attributes. For example, if we want to make our file hidden, we can simply use the following code.

fFile.Attributes = FileSystemAttributes.Hidden If (fFile.Attributes = FileSystemAttributes.Hidden) Then MessageBox.Show("This file is hidden.") Else MessageBox.Show("This file is not hidden.") End If

To reset the file and make it visible again, simply assign the Normal attribute.

fFile.Attributes = FileSystemAttributes.Normal

The DirectoryInfo Class Methods

The DirectoryInfo class methods are the key to understanding how to enumerate files and subdirectories. Take a moment to examine these methods and see how their signatures determine how they are used.

// Methods public void Create(); public virtual System.Runtime.Remoting.ObjRef CreateObjRef(Type requestedType); public System.IO.DirectoryInfo CreateSubdirectory(string path); public virtual void Delete(); public void Delete(bool recursive); public virtual bool Equals(object obj); public System.IO.DirectoryInfo[] GetDirectories(); public System.IO.DirectoryInfo[] GetDirectories(string searchPattern); public System.IO.FileInfo[] GetFiles(); public System.IO.FileInfo[] GetFiles(string searchPattern); public System.IO.FileSystemInfo[] GetFileSystemInfos(); public System.IO.FileSystemInfo[] GetFileSystemInfos(string searchPattern); public virtual int GetHashCode(); public virtual object GetLifetimeService(); public Type GetType(); public virtual object InitializeLifetimeService(); public void MoveTo(string destDirName); public void Refresh(); public virtual string ToString();

The following code creates a new instance of the DirectoryInfo class and assigns it to dDirectory. We use the GetFiles method of dDirectory to iterate through each file in the current directory and assign the current file to fFileInfo, which is an object of type FileInfo. We interrogate a few properties, FullName for one, and assign them to local variables. We then concatenate the information about each file to a string and display the result in a message box.

Dim dDirectory As New DirectoryInfo(".") Dim fFileInfo As FileInfo Dim sMessage As String For Each fFileInfo In dDirectory.GetFiles("*.*") Dim fName As String = fFileInfo.FullName Dim fSize As Long = fFileInfo.Length Dim fCreationTime As DateTime = fFileInfo.CreationTime sMessage += fSize & CtrlChrs.Tab & fCreationTime & _ CtrlChrs.Tab & fName & CtrlChrs.CrLf Next fFileInfo MessageBox.Show(sMessage, "More Framework Examples", _ MessageBoxButtons.OK, MessageBoxIcon.Information)

The output from this code is nicely formatted, as you can see in Figure 5-8. While not terribly complex, these examples illustrate how to use the WinCV tool to discover the framework classes you need to work with.

Figure 5-8

The DirectoryInfo class makes it easy to enumerate files and subdirectories.

tip

Get to know the framework classes, because understanding the .NET Framework classes is key to professional Visual Basic .NET programming. The WinCV tool makes it easy to discover how to use a framework class: simply find the class in WinCV and scan the constructors, fields, methods, and properties. We used both static and dynamic classes in our examples, so you should not have any problems using either in your own applications.



Coding Techniques for Microsoft Visual Basic. NET
Coding Techniques for Microsoft Visual Basic .NET
ISBN: 0735612544
EAN: 2147483647
Year: 2002
Pages: 123
Authors: John Connell

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