StreamWriter class in VB.NET

This article shows how to create a new text file and write a string to it.
  • 7161

Introduction

This article shows how to create a new text file and write a string to it. The StreamWriter class is used to write text to a stream. The StreamWriter class is a standard class within the System.IO namespace. or, Implements a TextWriter for writing characters to a stream in a particular encoding.

The most important methods of the StreamWriter class are Write and WriteLine.

Write Method -  Enables you to write a character, an array of characters, or a string.

WriteLine method  - Accepts a String and adds an end-of-line character to the end of the string.

Now add the references to the StreamWriter class.

Imports System.IO

 

Creating a StreamWriter

 

To create the StreamWriter, add the following line of code to the Main method of the program. If the filename specified already exists on your system, change the string parameter to another path.

 

Dim writer As New StreamWriter("D:\testfile.txt")

 

Writing Text to the File

Information can be written to the StreamWriter, and ultimately the file, using two of the class' methods. The WriteLine method stores an entire line of characters, ending with a carriage return in readiness for a new line. The simplest variation requires a string parameter containing the characters to be written.

 

writer.WriteLine("This is simple Text File")

        writer.WriteLine("-------------------")

        writer.Write("The date is: ")

        writer.WriteLine(DateTime.Now)

        writer.Close()

 

Text Encoding

 in this  example allows you to change the encoding method for the text written to the file. By default, the StreamWriter uses UTF-8 encoding. If you need to use an alternative standard, you can specify a third parameter that accepts an object of the Encoding class, from the Imports System.Text
namespace. the StreamWriter should use Unicode text.
 

Dim writer As New StreamWriter("D:\testfile.txt",True, Encoding.Unicode)

 

For Example

 

This example shows how to create a new text file and write a string to it.

 

Imports System.IO

Module Module1

    Sub Main()

        Dim writer As New StreamWriter("D:\testfile.txt")

        writer.WriteLine("This is simple Text File")

        writer.WriteLine("-------------------")

        writer.Write("The date is: ")

        writer.WriteLine(DateTime.Now)

        writer.Close()

    End Sub

End Module

 

Both WriteLine and Write can be used to output many other types of data, such as numbers, DateTime values and objects.

 

Conclusion:

The StreamWrite class is very useful for writing text to a stream. If there is any mistake in this article then please notify me. I expect your valuable comments and feedback about this article.

Categories

More Articles

© 2018 DotNetHeaven. All rights reserved.