kuanny kuanny - 6 months ago 40
Vb.net Question

Use vb.net to replace a tab delimited column of notepad text

i want check a specific column in notepad and replace all of them to zero , i have the following code

Dim vtext As String
Dim sum As Integer
Dim vstring(-1) As String
Dim p1 As String() = {vbTab}
Dim vData As String = ""

Using sr As New StreamReader("C:\Users\310238479\Desktop" + "\" + database(i) + ".txt")
While sr.Peek <> -1
lines.Add(sr.ReadLine)
End While
End Using
For Each line As String In lines
vstring = line.Split(p1, StringSplitOptions.RemoveEmptyEntries)
If (vstring.Length = 11) Then
If (vstring(10) <> "0") Then
vstring(10) = "0"
End If
End If
Next
Using sw As New StreamWriter("C:\Users\310238479\Desktop" + "\" + database(i) + ".txt")
For Each line As String In lines
sw.WriteLine(line)
Next
End Using


It is suppose to be working but somehow i cant get it to work , i guarantee the extension has no problem . Please give me some advise.

Answer

Firstly, this has nothing to do with Notepad. Notepad is simply a text file editor. There are numerous such applications around. A text file is a text file.

Secondly, instead of using loops to read and write lines to a file, just use File.ReadAllLines and File.WriteAllLines to do each in a single line of code.

As for the issue, your problem lies here:

For Each line As String In lines
    vstring = line.Split(p1, StringSplitOptions.RemoveEmptyEntries)
    If (vstring.Length = 11) Then
        If (vstring(10) <> "0") Then
            vstring(10) = "0"
        End If
    End If
Next

You loop through what is presumably a List(Of String) and, for each item, you split it into a String array and then possibly change one element of that array. That's all well and good but you then simply discard that array and make no change to your List(Of String) that you later write back to the file. If you want different text written back to the file then you have to actually change the text you write back to the file. That would mean replacing the original line with the concatenated contents of the modified array, e.g.

For i = 0 To lines.Count - 1
    vstring = lines(i).Split(p1, StringSplitOptions.RemoveEmptyEntries)

    If (vstring.Length = 11) AndAlso (vstring(10) <> "0") Then
        vstring(10) = "0"
        lines(i) = String.Join(ControlChars.Tab, vstring)
    End If
Next