How to write data to a file in VB.Net?
In Visual Basic.Net you can handle files via the System.IO namespace. For writing data to a file, you have to import this namespace first.
The steps to write to a file are:
- Define a streamwriter object
- Use the streamwriters methods to write the data
- Close the streamwriter object
Defining a streamwriter object
To define a streamwriter object you can use one of seven declarations. Differences include the encoding and the choice if you want to append data to the file or not. For a full description you can look on the MSDN-site concerning the Streamwriter-class.
Some examples:
Dim sw1 As New StreamWriter("C:\Test.txt", True) 'Open C:\test.txt and append subsequent writing to it
Dim sw2 as As New StreamWriter("C:\Test2.txt", False, System.Text.Encoding.ASCII) 'Open C:\test2.txt, don't append, use ASCII Encoding
Writing to a file
There are two methods to write to a file: Write and WriteLine. These methods have almost the same effect. WriteLine only places a vbNewLine after the data you write yourself.
Flushing and closing a file
If you write to a file, the data is not necessarily directly written to the disk. The systems writes first to a buffer. As soon as the buffer is full, the buffer is written to disk. You can define the buffersize during creation of the streamwriter. If for some reason you want to write the data to file, while using a buffer, you can use the Flush-method to flush the buffer to the disk.
To close the streamwriter use the method Close.
Example of writing to a file
In the following example, a file is opened. The user can type some string, which will be written to file every second line, wether the buffer is full or not. If the user enters an empty line, the file will be closed.
Dim MyStreamWriter As New StreamWriter("C:\test.txt",False)
Dim LineToWrite as String = ""
Dim LineCounter as integer = 0
Do
LineToWrite = Inputbox ("Enter text, leave blank to stop")
If LineToWrite = "" Then Exit Do
MyStreamWriter.WriteLine(LineToWrite)
LineCounter += 1
If LineCounter >= 2 Then
MyStreamWriter.Flush
LineCounter =0
End If
Loop Until LineToWrite = ""
MyStreamWriter.Close()
|