我在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
当我运行它时,它会给我一个错误:
"startIndex cannot be larger than length of string."
我做错了什么?
答案 0 :(得分:1)
有几条注释没有意义,就像循环结束时发生的错误或者检查字符串长度会导致文件访问错误一样。试试这个:
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