I have a text file containing the data in following format
12345 Abdt3 hy45d et45a 76huj agsj7
Now I want to replace hy45d with another sting that is created on run time. But I am not finding any way to do it. It keep replacing the firt item or append it in next line.
Can any one plz help me resolve this issue
Code that I am using is
Public Sub SaveToTextFile(ByVal PNR As String, ByVal CaseCount As Integer, ByVal Type As String)
'- Location of the Text files
Dim targetFile As String = "C:\TestReport\TextFiles\PNR.txt"
'- Open the target file/stream
Dim sw As StreamWriter = New StreamWriter(targetFile, True)
' Try
If (CaseCount = 0 And Type = 1) Then
sw.Write(PNR, 0, 6)
ElseIf (CaseCount = 1 And Type = 1) Then
sw.WriteLine(PNR, 6, 7)
ElseIf (CaseCount = 2 And Type = 1) Then
sw.WriteLine(PNR, 13, 7)
ElseIf (CaseCount = 3 And Type = 1) Then
sw.WriteLine(PNR, 20, 7)
ElseIf (CaseCount = 0 And Type = 2) Then
sw.WriteLine(PNR, 27, 7)
ElseIf (CaseCount = 1 And Type = 2) Then
sw.WriteLine(PNR, 34, 7)
ElseIf (CaseCount = 2 And Type = 2) Then
sw.WriteLine(PNR, 41, 7)
ElseIf (CaseCount = 3 And Type = 2) Then
sw.WriteLine(PNR, 48, 7)
ElseIf (CaseCount = 0 And Type = 3) Then
sw.WriteLine(PNR, 55, 7)
ElseIf (CaseCount = 1 And Type = 3) Then
sw.WriteLine(PNR, 62, 7)
ElseIf (CaseCount = 2 And Type = 3) Then
sw.WriteLine(PNR, 69, 7)
ElseIf (CaseCount = 3 And Type = 3) Then
sw.WriteLine(PNR, 76, 7)
End If
'Catch ex As Exception
' Console.Write(ex.ToString())
'End Try
sw.Close()
End Sub
There is no good way of doing this. Text files may use encodings that allocate more than one byte for a character. Simply put, even if you know the character position of the target string, you don’t (in general) know its byte position.
The .NET classes therefore reasonably forbid random access on text files. The standard way of coping with this is to read the whole (or at least part) of the text file, change the string, and write the changed string back.
So:
Short and sweet.
Or, if you want to search by column: