Write Text to a Text File with Stream Writer Class using VB.NET

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (3 votes, average: 4.33 out of 5)
 

This will use the Stream Writer class under the System.IO namespace to write text to a textfile.

        '
        'Write to text file with the Stream Writer Class
        Dim sWriter As IO.StreamWriter = New IO.StreamWriter("c:\newTextFile.txt")

        'This is pretty much easy to understand. No explanation 
        sWriter.WriteLine("Hi")

        sWriter.WriteLine("Testing out this code")

        sWriter.WriteLine("Hopefully this code will work")

        sWriter.WriteLine("Lets flush the stream and see")

        'Flush all data to the file.   
        sWriter.Flush()

        sWriter.Close()

12 thoughts on “Write Text to a Text File with Stream Writer Class using VB.NET

  1. Anonymous

    Dim sw As IO.StreamWriter = IO.File.CreateText(“c:\Users\Mugdho\Desktop\aad.txt”)

    sw.WriteLine(“Md Monir Hossain”)

    sw.WriteLine(“Occupation: Student”)

    sw.WriteLine(“College: Blakehall College”)

    sw.WriteLine(“abcdefghijklmnopqrst…”)

    sw.Close()
    End Sub

    Reply
  2. gh

    For some reason I can’t get Jason’s solution to work. Get “access to the path c:\test.txt is denied”. Help.
    Dim sWriter As IO.StreamWriter = New IO.StreamWriter(“c:\testfile.txt”)

    Private Sub btnCreateFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCreateFile.Click
    sWriter.WriteLine(“Testing out this code”)
    ‘Flush all data to the file.
    sWriter.Flush()
    sWriter.Close()
    End Sub

    Reply
  3. Pieter-Jan

    Thank you very much! 🙂
    You solved my solution.

    For the access to the path c:\test.txt is denied: specify another directory.

    Thanks!

    Reply
  4. Hibbity

    Wow!!!

    You have no idea how long it took me to solve my problem of producing a text file for use as a fortran program input file that didn’t make the fortran go haywire!

    Don’t know exactly why this code works, but it does and I will definitely sleep well tonight 🙂

    Reply

Leave a Reply

Your email address will not be published.