Input and Output
  Read a text file
  List a directory
  Create a log file
  Read and write large files
  Read and write binary data
  Watch file system changes

Get URL for this page

How Do I...Create a log file?

This sample illustrates how to create a basic log file using the IO classes. This demonstration introduces many useful concepts such as writing to a file, and opening a file, even if the file does not yet exist. Since the information written to the file needs to be shown to the user, this example also demonstrates reading a file.

 
VB Logfile.aspx

[Run Sample] | [View Source]

Reading and writing information to and from a file is a common task, which you will no doubt come across when programming. Many programs regularly deal with reading and writing (Microsoft Excel, Microsoft Word, or Microsoft Powerpoint are a few examples). This example shows how to create log file that is a text file (as opposed to a binary file), so you can open and read the file.

The example shows you how to create a FileStream object. A FileStream holds a reference to a file that you can manipulate. There are a few things that the FileStream needs to be given when making a reference to our file. First, it needs the name of the file. Next, you have to designate to the FileStream the mode in which you want to refer to our file. We could ask it to only open an existing file, but that means if the file does not exist, it will cause a problem. Therefore, we are going to tell the FileStream to open the existing file if it is there, or create a new file if it is not. Finally, you have to designate to the FileStream the kind of access you want to the file (read, or write). This example will demonstrate reading and writing.


            ' make a new FileStream object, ready for read and write steps. 
            Dim fs As FileStream = New FileStream(Environment.GetEnvironmentVariable("TEMP") & _ 
            "\\qslogfileVB.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite)
        
VB

Now that you have a reference to your file, the next step is to write some log information into it. To do this, you need to create a StreamWriter, an object that can write a string into a Stream object. If you are familiar with the FileStream object, you might be wondering why we do not use its Write method. Why make the StreamWriter object at all? Because a FileStream can only write an array of bytes to a file, and many times (as in this example) you might want to write other kinds of data, such as strings. A StreamWriter can write strings to our file, while our FileStream cannot. This is going to make your job a lot easier.

The following segment demonstrates how to create a new StreamWriter. Notice that the StreamWriter is made with a reference to the stream. Having made the stream, you can use the Seek method to get to the end of the file (if you do not do this, and the file already exists, you would be putting your new information in the wrong place), then use the Write method to write your strings into the file. Note that Write itself does not guarantee that the strings get into the file, therefore to force the information through the FileStream, invoke the Flush method on your Writer .


            Dim w As StreamWriter = New StreamWriter(fs) ' create a stream writer 
            w.BaseStream.Seek(0, SeekOrigin.End) ' set the file pointer to the end of file 
            w.Write("Log Entry : {0}", vbcrlf) w.WriteLine("{0} {1}{2}", 
            DateTime.Now.ToLongTimeString(), DateTime.Now.ToLongDateString(), vbcrlf) 
            w.WriteLine("--Log Entry goes here--") w.Flush() ' update underlying file
        
VB

At this point, you have finished updating your log file. Normally, you would shut the file so anyone can open it and see the log entries. To read the file, you have to make a StreamReader. Again, the FileStream does have a Read method, although creating a StreamReader makes this easier. Having made the StreamReader , you need to point it to some place in your file, although this time you are going to move to the beginning of the file and move from there.

In order to determine when you have reached the end of the file, you have to 'peek' at the file from the current position of the StreamReader current position. If you have reached the end of the file (signified by a value less than zero), it does not keep reading the file since there is no information left. However, if there is still some information to read, you can instruct your reader to get the next line of information, using its ReadLine method. Once finished, you can close the Stream, the Reader, and the Writer .


            Dim r As StreamReader = New StreamReader(fs) ' create a Char reader 
            r.BaseStream.Seek(0, SeekOrigin.Begin) ' set the file pointer to the beginning 
            While r.Peek() > -1 ' while not at the end of the file 
            output.Append(r.ReadLine()) ' get the next line of information from the file 
            output.Append( chr(13) ) ' a newline End While w.Close() ' close the writer and 
            underlying file r.Close() ' close the read
        
VB

The result is a readable file. This functionality is ideal for server administrators as well as those who maintain websites. You can track performance information, the number of hits for a site, as well as numerous other logging tasks that do not require a database.


Copyright 2001-2002 Microsoft Corporation. All rights reserved.