reading and writing text files with vb

Upload: hoai-nguyen

Post on 09-Apr-2018

217 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/8/2019 Reading and Writing Text Files With VB

    1/4

    Reading and writing text files with

    VB.NET

    By Bruce Walton, Builder.com | 2002/08/13 14:10:00

    Tags: .net,coding, microsoft .net,programming, text files,vb,vb.net,windowsprogramming

    Change the text size: a | A

    Print this E-mail this Leave a comment Clip this

    Reading and writing text files is an essential task in any programming language. Followthis step-by-step approach to working with text files in VB .NET.

    Years ago, when I first learned to program in BASIC, I came across a sample program forreading a text file. The OPEN command with the file number looked quite confusing, so Inever wrote the program. Later, when I learned Visual Basic, I was shocked to see thatthe same file operations existed in VB. The basic file-handling commands had notchanged; just a few more features had been added.

    With Visual Basic .NET, Microsoft introduced a new, object-oriented method forworking with files. The System.IO namespace in the .NET framework provides severalclasses for working with text files, binary files, directories, and byte streams. I will lookspecifically at working with text files using classes from the System.IO namespace.

    Basic methodsBefore we jump into working with text files, we need to create a new file or open anexisting one. That requires the System.IO.File class. This class contains methods formany common file operations, including copying, deleting, file attribute manipulation,and file existence. For our text file work, we will use the CreateText and OpenTextmethods.

    WEEKLY .NET HOW-TOS

    New .NET tutorials updated every Thusday withCast Your .NET

    CreateTextTrue to its name, the CreateText method creates a text file and returns aSystem.IO.StreamWriter object. With the StreamWriter object, you can then write to the

    http://www.builderau.com.au/program/windows/email.htm?TYPE=editor&AT=320267367-339024644t-320000994chttp://www.builderau.com.au/tag/.net.htmhttp://www.builderau.com.au/tag/.net.htmhttp://www.builderau.com.au/tag/coding.htmhttp://www.builderau.com.au/tag/microsoft_.net.htmhttp://www.builderau.com.au/tag/programming.htmhttp://www.builderau.com.au/tag/programming.htmhttp://www.builderau.com.au/tag/text_files.htmhttp://www.builderau.com.au/tag/vb.htmhttp://www.builderau.com.au/tag/vb.htmhttp://www.builderau.com.au/tag/vb.net.htmhttp://www.builderau.com.au/tag/vb.net.htmhttp://www.builderau.com.au/tag/vb.net.htmhttp://www.builderau.com.au/tag/windows_programming.htmhttp://www.builderau.com.au/tag/windows_programming.htmhttp://www.builderau.com.au/program/windows/print.htm?TYPE=story&AT=320267367-339024644t-320000994chttp://www.builderau.com.au/program/windows/email.htm?TYPE=story&AT=320267367-339024644t-320000994chttp://www.builderau.com.au/program/windows/soa/Reading-and-writing-text-files-with-VB-NET/0,339024644,320267367,00.htm#leaveyourcommenthttp://void%280%29/http://www.builderau.com.au/castyournet/?feed=wtkmhttp://www.builderau.com.au/castyournet/?feed=wtkmhttp://www.dzone.com/links/add.htmlhttp://www.stumbleupon.com/submit?url=http://www.builderau.com.au%2Fprogram%2Fwindows%2Fsoa%2FReading-and-writing-text-files-with-VB-NET%2F0%2C339024644%2C320267367%2C00.htm&title=Reading+and+writing+text+files+with+VB.NEThttp://slashdot.org/bookmark.pl?url=http://www.builderau.com.au%2Fprogram%2Fwindows%2Fsoa%2FReading-and-writing-text-files-with-VB-NET%2F0%2C339024644%2C320267367%2C00.htm&title=Reading+and+writing+text+files+with+VB.NEThttp://reddit.com/submit?url=http://www.builderau.com.au%2Fprogram%2Fwindows%2Fsoa%2FReading-and-writing-text-files-with-VB-NET%2F0%2C339024644%2C320267367%2C00.htm&title=Reading+and+writing+text+files+with+VB.NEThttp://digg.com/submit?phase=2&url=http://www.builderau.com.au%2Fprogram%2Fwindows%2Fsoa%2FReading-and-writing-text-files-with-VB-NET%2F0%2C339024644%2C320267367%2C00.htm&title=Reading+and+writing+text+files+with+VB.NET&bodytext=Reading+and+writing+text+files+is+an+essential+task+in+any+programming+language.+Follow+this+step-by-step+approach+to+working+with+text+files+in+VB+.NET.http://del.icio.us/posthttp://www.builderau.com.au/program/windows/email.htm?TYPE=editor&AT=320267367-339024644t-320000994chttp://www.builderau.com.au/tag/.net.htmhttp://www.builderau.com.au/tag/coding.htmhttp://www.builderau.com.au/tag/microsoft_.net.htmhttp://www.builderau.com.au/tag/programming.htmhttp://www.builderau.com.au/tag/text_files.htmhttp://www.builderau.com.au/tag/vb.htmhttp://www.builderau.com.au/tag/vb.net.htmhttp://www.builderau.com.au/tag/windows_programming.htmhttp://www.builderau.com.au/tag/windows_programming.htmhttp://www.builderau.com.au/program/windows/print.htm?TYPE=story&AT=320267367-339024644t-320000994chttp://www.builderau.com.au/program/windows/email.htm?TYPE=story&AT=320267367-339024644t-320000994chttp://www.builderau.com.au/program/windows/soa/Reading-and-writing-text-files-with-VB-NET/0,339024644,320267367,00.htm#leaveyourcommenthttp://void%280%29/http://www.builderau.com.au/castyournet/?feed=wtkm
  • 8/8/2019 Reading and Writing Text Files With VB

    2/4

    file. The following code demonstrates how to create a text file:Dim oFile as System.IO.FileDim oWrite as System.IO.StreamWriteroWrite = oFile.CreateText(C:\sample.txt)OpenText

    The OpenText method opens an existing text file for reading and returns aSystem.IO.StreamReader object. With the StreamReader object, you can then read thefile. Lets see how to open a text file for reading:Dim oFile as System.IO.FileDim oRead as System.IO.StreamReaderoRead = oFile.OpenText(C:\sample.txt)Writing to a text file

    The methods in the System.IO.StreamWriter class for writing to the text file are Writeand WriteLine. The difference between these methods is that the WriteLine method

    appends a newline character at the end of the line while the Write method does not. Bothof these methods are overloaded to write various data types and to write formatted text tothe file. The following example demonstrates how to use the WriteLine method:oWrite.WriteLine(Write a line to the file)oWrite.WriteLine() Write a blank line to the fileFormatting the output

    The Write and WriteLine methods both support formatting of text during output. Theability to format the output has been significantly improved over previous versions ofVisual Basic. There are several overloaded methods for producing formatted text. Letslook at one of these methods:

    oWrite.WriteLine({0,10}{1,10}{2,25}, Date, Time, Price)oWrite.WriteLine({0,10:dd MMMM}{0,10:hh:mm tt}{1,25:C}, Now(), 13455.33)oWrite.Close()

    The overloaded method used in these examples accepts a string to be formatted and thena parameter array of values to be used in the formatted string. Lets look at both linesmore carefully.

    The first line writes a header for our report. Notice the first string in this line is {0,10}{1,10}{2,25}. Each curly brace set consists of two numbers. The first number is the indexof the item to be displayed in the parameter array. (Notice that the parameter array is zerobased.) The second number represents the size of the field in which the parameter will beprinted. Alignment of the field can also be defined; positive values are left aligned andnegative values are right aligned.

    The second line demonstrates how to format values of various data types. The first fieldis defined as {0,10:dd MMMM}. This will output todays date (retrieved using the Now()function) in the format 02 July. The second field will output the current time formatted as02:15 PM. The third field will format the value 13455.33 into the currency format as

  • 8/8/2019 Reading and Writing Text Files With VB

    3/4

    defined on the local machine. So if the local machine were set for U.S. Dollars, the valuewould be formatted as $13,455.33.

    Listing A shows the output of our sample code.

    Listing A

    Date Time Price22 July 10:58 AM $13,455.33

    Reading from a text fileThe System.IO.StreamReader class supports several methods for reading text files andoffers a way of determining whether you are at the end of the file that's different fromprevious versions of Visual Basic.

    Line-by-lineReading a text file line-by-line is straightforward. We can read each line with a ReadLinemethod. To determine whether we have reached the end of the file, we call the Peekmethod of the StreamReader object. The Peek method reads the next character in the filewithout changing the place that we are currently reading. If we have reached the end ofthe file, Peek returns -1. Listing B provides an example for reading a file line-by-lineuntil the end of the file.

    Listing B

    oRead = oFile.OpenText(-C:\sample.txt")

    While oRead.Peek -1LineIn = oRead.ReadLine()

    End While

    oRead.Close()

    An entire fileYou can also read an entire text file from the current position to the end of the file byusing the ReadToEnd method, as shown in the following code snippet:Dim EntireFile as StringoRead = oFile.OpenText(C:\sample.txt)EntireFile = oRead.ReadToEnd()

  • 8/8/2019 Reading and Writing Text Files With VB

    4/4

    This example reads the file into the variable EntireFile. Since reading an entire file canmean reading a large amount of data, be sure that the string can handle that much data.

    One character at a timeIf you need to read the file a character at a time, you can use the Read method. This

    method returns the integer character value of each character read. Listing C demonstrateshow to use the Read method.

    Listing C

    Dim intSingleChar as Integer

    Dim cSingleChar as String

    oRead = oFile.OpenText(-C:\sample.txt")

    While oRead.Peek -1

    intSingleChar = oRead.Read()

    ' Convert the integer value into a character

    cSingleChar = Chr(intSingleChar)

    End While

    Tap into the power

    We've barely scratched the surface of the new file functionality included in .NET, but atleast you have an idea of the power now available in the latest edition of Visual Basic.The abilities of the classes in the System.IO namespace are quite useful, but if you wantto continue to use the traditional Visual Basic file operations, those are still supported.