"Index was outside the bounds of the array" 访问变量时
"Index was outside the bounds of the array" when accessing variable
尝试将其设置为单击一个按钮,它可以让您选择一个目录,该目录,然后该目录,.file,由特定行更改。当前代码。抱歉我是菜鸟
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim dialog As New OpenFileDialog()
If DialogResult.OK = dialog.ShowDialog Then
TextBox1.Text = dialog.FileName
Dim Directory1 As String
Directory1 = Trim(TextBox1.Text)
Dim Item1 As String
Item1 = Trim(TextBox2.Text)
Dim thefile As String = Directory1
Dim lines() As String = System.IO.File.ReadAllLines(Directory1)
// This gets the error. Item1.
// {"Index was outside the bounds of the array."}
lines(2) = Item1
System.IO.File.WriteAllLines(thefile, lines)
End If
End Sub
问题是文件没有在数组 lines()
上分配足够的行,可能是因为 System.IO.File.ReadAllLines(Directory1)
读取的行少于三行。尝试使用超过 3 行的文件,它应该可以工作。
您也可以这样做(抱歉,我不是 vb.net 编码员,所以我的语法可能有误):
If lines.Length < 3 Then
ReDim Preserve lines(2)
End If
lines(2) = Item1
我不太确定你想用这个实现什么,所以我不能给 "solution"。这只是一个 "patch" 让你的代码工作。
更新
根据评论中的要求,如果您希望在变量中更改行(在 TextBox3.Text
中,从零开始),您需要这样做:
Dim LineToBeChanged As Integer = Convert.toInt32(TextBox3.Text)
If lines.Length < LineToBeChanged+1 Then
ReDim Preserve lines(LineToBeChanged)
End If
lines(LineToBeChanged) = Item1
尝试将其设置为单击一个按钮,它可以让您选择一个目录,该目录,然后该目录,.file,由特定行更改。当前代码。抱歉我是菜鸟
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim dialog As New OpenFileDialog()
If DialogResult.OK = dialog.ShowDialog Then
TextBox1.Text = dialog.FileName
Dim Directory1 As String
Directory1 = Trim(TextBox1.Text)
Dim Item1 As String
Item1 = Trim(TextBox2.Text)
Dim thefile As String = Directory1
Dim lines() As String = System.IO.File.ReadAllLines(Directory1)
// This gets the error. Item1.
// {"Index was outside the bounds of the array."}
lines(2) = Item1
System.IO.File.WriteAllLines(thefile, lines)
End If
End Sub
问题是文件没有在数组 lines()
上分配足够的行,可能是因为 System.IO.File.ReadAllLines(Directory1)
读取的行少于三行。尝试使用超过 3 行的文件,它应该可以工作。
您也可以这样做(抱歉,我不是 vb.net 编码员,所以我的语法可能有误):
If lines.Length < 3 Then
ReDim Preserve lines(2)
End If
lines(2) = Item1
我不太确定你想用这个实现什么,所以我不能给 "solution"。这只是一个 "patch" 让你的代码工作。
更新
根据评论中的要求,如果您希望在变量中更改行(在 TextBox3.Text
中,从零开始),您需要这样做:
Dim LineToBeChanged As Integer = Convert.toInt32(TextBox3.Text)
If lines.Length < LineToBeChanged+1 Then
ReDim Preserve lines(LineToBeChanged)
End If
lines(LineToBeChanged) = Item1