Reputation: 39
Trying to make it where, you click a button, it lets you pick a directory, the directory, and then that directory, .file, is changed by the specific line. Current code. Sorry i'm a noob.
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
Upvotes: 2
Views: 391
Reputation: 28272
The problem is that the file is not allocating enough lines on the array lines()
, probably because System.IO.File.ReadAllLines(Directory1)
is reading less than three lines. Try using a file with more than 3 lines and it should work.
You could also do something like this (sorry, I'm no vb.net coder so my syntax could be wrong):
If lines.Length < 3 Then
ReDim Preserve lines(2)
End If
lines(2) = Item1
I'm not exactly sure what do you want to achieve with this so I can't give a "solution". This would be just a "patch" to make your code work.
From requirements in the comments, if you want the line to be changed in a variable (which would be in TextBox3.Text
, starting from zero), you'd need to do this:
Dim LineToBeChanged As Integer = Convert.toInt32(TextBox3.Text)
If lines.Length < LineToBeChanged+1 Then
ReDim Preserve lines(LineToBeChanged)
End If
lines(LineToBeChanged) = Item1
Upvotes: 1