|
-
Dec 2nd, 2005, 04:13 PM
#1
Thread Starter
Frenzied Member
[VB.NET] How do I read/write to a text file?
This question comes up all the time. The .NET framework provides easy to use classes for reading and writing to text files.
The Classes to use are the StreamReader and StreamWriter classes, which are found in the System.IO namespace. If you are going to be using lots of file access methods in your program, you can qualify the namespace by adding
to your program, before any class definitions.
Otherwise, you can access the StreamReader and StreamWriter classes by qualifying them within your program. For example
VB Code:
Dim SR As IO.StreamReader
Using them is fairly straightforward, but one key thing must be kept in mind. That is, that they are for sequential reading and writing. If you wish to open an existing file, and replace some line in the middle, you're going to have to do a little more work, or treat the text file as a Database and use ADO.NET to access it.
StreamReaders read line by line, and StreamWriters write Line by Line.
Here is a basic example of reading using a streamreader:
VB Code:
Private Sub ReadFromTextFile()
Dim myReadFilePath As String = Application.StartupPath + "\MyTextFile.TXT"
'This is how to point to a file in the same directory as your program
'I almost always put my reader routines in an IF statement, so that I don't throw
'an exception.
If IO.File.Exists(myReadFilePath) Then
Dim sr As New IO.StreamReader(myReadFilePath) 'Any string value with a file path
'For this example, we will read the Text file into a RichTextBox
While Not (sr.Peek = -1)
'The Peek method checks to see if there is more text coming
'Without advancind the StreamReader, and returns -1 if the end of file is reached.
'Alternatively, you could use a for loop, etc, if you wanted to read a specific
'Number of lines.
RichTextBox1.SelectedText = sr.ReadLine() + Environment.NewLine
'The ReadLine Method advances the streamreader one line, and returns the value of
'The string read from the file.
'The Environment.NewLine simply adds a new line to the RichTextBox we are using
End While
sr.Close()
End If
End Sub
Now let's say you want to do multiple things with each line read in. It's important to note that each time StreamReader.ReadLine() is called, it returns a new line from the text file. So for instance, while the below code will compile, it will not give the anticipated result:
VB Code:
Private Sub BuggyReadMethod()
Dim myReadFilePath As String = Application.StartupPath + "\MyTextFile.TXT"
If IO.File.Exists(myReadFilePath) Then
Dim sr As New IO.StreamReader(myReadFilePath) 'Any string value with a file path
Dim strArray(10) As String
While Not (sr.Peek = -1)
Dim s As String = sr.ReadLine().Replace("info", "Information")
strArray = sr.ReadLine().Split(" "c) 'Put each word into the string array
End While
'While that will compile just fine, the ReadLine Method is called twice - so
'It will advance the StreamReader two times, giving different strings each time.
End If
End Sub
So, if within your read loop, you wish to do more than one thing with the read in line, you must put it in a string variable first, like this:
VB Code:
Private Sub BetterReadMethod()
Dim myReadFilePath As String = Application.StartupPath + "\MyTextFile.TXT"
If IO.File.Exists(myReadFilePath) Then
Dim sr As New IO.StreamReader(myReadFilePath)
Dim strArray(10) As String
While Not (sr.Peek = -1)
Dim Line As String
Line = sr.ReadLine()
Line = Line.Replace("info", "Information")
strArray = Line.Split(" "c) 'Put each word into the string array
End While
End If
End Sub
The StreamReader class also exposes a ReadToEnd method, which will return the entire value of the textfile from whatever point in it the streamreader is at. This can be used for optimizing read speed, and when you have a variable that can accept a large string with newLine characters in it (such as a richtextbox)
VB Code:
Private Sub ReadToEndExample()
Dim myReadFilePath As String = Application.StartupPath + "\MyTextFile.TXT"
If IO.File.Exists(myReadFilePath) Then
Dim sr As New IO.StreamReader(myReadFilePath)
'You could optionally read in some header data, or whatever before calling readtoEnd
Dim headerstring As String = sr.ReadLine()
RichTextBox1.SelectedText = sr.ReadToEnd 'This wil return all data from the second line until the end of file.
sr.Close()
End If
End Sub
That's pretty much it for the StreamReader, for basic uses.
The StreamWriter works almost exactly the same. The following example opens up a new file, and writes a few lines of text in it. Note the difference between Write and WriteLine is only that a newline character is written with the WriteLine method.
VB Code:
Private Sub WriteTextFile()
Dim myWritePath As String = Application.StartupPath + "\myoutputFile.txt"
Dim sw As New IO.StreamWriter(myWritePath)
'Now, we just start writing stuff.
sw.WriteLine("This is some info to put in a text file.")
'The Write method will not put a new line character, like this:
sw.Write("This is")
sw.WriteLine(" some other info, using a write statement")
sw.Close() 'If this is not placed, the file will not save, and you will have an empty file.
End Sub
Make sure you call StreamWriter.Close(), otherwise your efforts will be wasted on an empty file! The above program outputs a file with this inside of it:
Code:
This is some info to put in a text file.
This is some other info, using a write statement
Notice the second line is compounded because of the use of Write instead of WriteLine.
Sometimes you may wish to only add to a file, such as in the case of a log file, or a history file, etc.. The method for this is also fairly easy, and involves only adding one additional variable to the constructor of the StreamWriter, as in the below example.
VB Code:
Private Sub WriteAppendedText()
Dim myWritePath As String = Application.StartupPath + "\myLogFile.Log"
'Here is a method for writing a log file, using the append mode of the
Dim sw As New IO.StreamWriter(myWritePath, True)
'The second parameter (True) in this overloaded constructor is a boolean value
'That tells the streamwriter to Append if the file exists.
'Note that if it doesn't exist, it will simply start a new file.
'Calling the IO.File.Exists method may be appropriate if you need to be appending
'an existing file
sw.WriteLine(DateTime.Now.ToShortTimeString + " " + DateTime.Now.ToShortDateString + ": Appended the log file.")
'The above line simply adds the time and date, and a short message to an existing file.
End Sub
So, that's it for sequential reading and writing. Now quite often, as mentioned in the introduction, you might want to open a file, scan for something, and replace it. You can do this with the StreamReader and StreamWriter, but note that neither can do the full job, and you will need both. The following example uses a temporary file, and overwrites the original with the temporary file after it is finished using the IO.File.Copy method.
VB Code:
Private Sub FindAndReplace()
Dim MyTempFile As String = "tempfile.txt"
Dim MyFile As String = Application.StartupPath + "\Appdata.txt"
If IO.File.Exists(MyFile) Then
Dim sr As New IO.StreamReader(MyFile)
Dim sw As New IO.StreamWriter(MyTempFile)
'The below example replaces all instances of the word Bill with William.
While Not (sr.Peek = -1)
Dim Line As String = sr.ReadLine 'read into a string
Line = Line.Replace("Bill", "William") 'Do the work with the string
sw.WriteLine(Line) 'Write the new line
End While
sr.Close()
sw.Close()
'Occasionally, the StreamReader destructor doesn't let go of the file quick enough
'to use it again. To remedy this, you can use the GC.Collect() Method to force the
'Program to clean up resources
GC.Collect()
IO.File.Copy(MyTempFile, MyFile, True) 'True specifies to overwrite.
End If
End Sub
That's it! If someone would like to add in how to do it via ADO.NET, that might be nice to have too.
Additional information on the StreamReader class can be found on MSDN here and additonal info on the StreamWriter class can be found here
Bill
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|