Dylan de St Pern
Dylan de St Pern

Reputation: 469

vb.net appendline substring error

I have this code in vb:

Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles browsebtn.Click
    OpenFileDialog1.Filter = "Text Files|*.txt"
    OpenFileDialog1.Title = "Select Log File"
    If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
        Dim filename As String = OpenFileDialog1.FileName
        Using streamreader As New StreamReader(filename)
            While streamreader.Read
                Dim line As String = streamreader.ReadLine()
                Dim date1 As String = line.Substring(6, 6)
                Dim writer = New StreamWriter("c:\" + date1 + ".txt")
                writer = File.AppendText(line)
                writer.Close()
            End While
        End Using

    End If
End Sub
End Class

When I run it, it gives me an error:

"startIndex cannot be larger than length of string."

What am I doing wrong?

Upvotes: 0

Views: 100

Answers (1)

Several comments make no sense like the error happening at the end of the loop or how checking a string length can result in a File Access error. Try something this:

  Dim Line as String           
  Dim Date1 As String

  While streamreader.Read
     Line = streamreader.ReadLine()
     If Line.Length > 12 Then
         date1  = line.Substring(6, 6)
         Using sw As New StreamWriter("c:\" + date1 + ".txt")
             sw.Write(line)
         End Using
     End If
  End While

Upvotes: 1

Related Questions