Question Problem getting Streamwriter to write to a text file

maxedev

Member
Joined
Sep 3, 2010
Messages
8
Programming Experience
Beginner
Hello,

I'm fairly new to vb.net and am encountering a problem when trying to write data to a text file. If I put the output into a messagebox I can see it, but when I attempt to write it to a file it is just blank. What am I missing here? EDIT - This is just a simple winform that I specify a path to a local HTML file in Textbox1 and I'm attempting to parse some HREF tag data. Thanks in advance.

VB.NET:
Imports System.IO
Imports System.Text.RegularExpressions

Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click


        Dim sr As New StreamReader(TextBox1.Text)

        Dim input As String
        Do
            input = sr.ReadLine
            If input IsNot Nothing Then

                dumpHREF(input)

            End If
        Loop Until input Is Nothing

        sr.Close()

    End Sub
    Sub dumpHREF(ByVal inputString As String)
        Dim r As Regex
        Dim m As Match
        Dim sw As New StreamWriter("c:\html.txt")

        r = New Regex(("href\s*=\s*(?:""(?<1>[^""]*)""|(?<1>\S+))"), RegexOptions.IgnoreCase Or RegexOptions.Compiled)
        m = r.Match(inputString)
        While m.Success
            MessageBox.Show("found href " & m.Groups(1).Value & " at " & m.Groups(1).Index.ToString())
            sw.WriteLine("found href " & m.Groups(1).Value & " at " & m.Groups(1).Index.ToString())
            m = m.NextMatch

        End While

        sw.Close()

    End Sub
End Class
 
The reason you are not getting anything in your output file is that you are creating a new instance of the Streamwriter for every line you are reading. I would advise that you open your StreamReader and StreamWriter, read a line of input, check your RegEx and if it passes write the line to the StreamWriter. Then read the next line etc. If you need more help with the code, let us know.

Also, take a look and think about your looping and use of While (particularly the
VB.NET:
While m.Success
...
End While
and
VB.NET:
Do
... 
Loop Until input is Nothing
).
 
"While m.Success" is ok because there could be multiple 'href's in a line, but you're right there should only be create one file and all line matches written to it. Alternative is to use the append parameter for StreamWriter constructor, but opening the file for writing once is preferred.
"Until input is Nothing" is also ok since that mean end of read stream.
 
Back
Top