Reputation: 41
I would like to edit specific line in text file using vb.net. Example below is my data in text file:
Port1.txt
data1
data2
data3
data4
data5
data6
data7
I would like to edit data5 (line 5) in the text file to dataXX. How do I do that?
So far by using the code below, I only can access all the data listed instead of a row data.
Dim path As String = "c:\Users\EliteBook\Desktop\Port1.txt"
Dim readText() As String = File.ReadAllLines(path)
Dim s As String
For Each s In readText
MsgBox(s)
Next
This would give me an output in msgbox of all the data listed in the text file. How do I access a specific row of data instead of all of it? I have edited this question according to Nahum Litvin suggestion via here
Upvotes: 1
Views: 114
Reputation: 28530
Nahum's answer is correct, but it's in C#. Here is the equivalent VB.NET, using the data in the code you posted in your question:
Dim path As String = "c:\Users\EliteBook\Desktop\Port1.txt"
Dim readText As String() = File.ReadAllLines(path)
readText(4) = "dataXX"
File.WriteAllLines(path, readText)
The above code reads the file into an array of string, one line per element. It then changes element 4 (the 5th line) to "dataXX", in this line of code:
readText(4) = "dataXX"
Then it saves the array back to the file, with line 5 reading "dataXX".
Upvotes: 2
Reputation: 7197
ur using the wrong methods.
http://msdn.microsoft.com/en-us/library/s2tte0y1(v=vs.110).aspx
approxemently like this I have no compiler at hand
string path = @"c:\temp\MyTest.txt";
string[] readText = File.ReadAllLines(path);
string[4] = "new data";
File.WriteAllLines(path, readText );
Upvotes: 2