Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

System I.O - replace lines in a text file 1

Status
Not open for further replies.

davida37

IS-IT--Management
May 10, 2006
113
GB
Hi,

Using VB.NET 2005. I am trying to create a sub which loops through each line in a text file and does a string replace on a certain word. The sub also needs to log the line number/s which have changed and write these to a log file.

All the examples I have seen so far use the following method which reads the whole file into a string variable - does the string replace and then pumps the whole lot out to the file. This has the right result but can not log the file line number/s which were changed. i.e.


Dim Fs As FileStream = New FileStream(“C:\sample.txt”), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite)
Dim sw As New StreamWriter(Fs)
Dim sr As New StreamReader(Fs)
Dim str As String

str = sr.ReadToEnd()
str = str.Replace(LCase("TEST"), LCase("xxx"))
Fs.Position = 0
Fs.SetLength(str.Length)
sw.Write(str)
sw.Flush()

sw.Close()
Fs.Close()

I think I need to use the sr.ReadLine() to loop through each line - see if the line contains the word I am looking for - if it does - do a string replace on that line and write the new line to the text file + log line number to file. Is this possible?

thanks
david
 
Yes, it is possible.

Dim Fs As FileStream = New FileStream("C:\sample.txt"), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite)
Dim sw As New StreamWriter(Fs)
Dim sr As New StreamReader(Fs)
Dim str As String
Dim NumReplaced As Integer = 0

Do While sr.Peek <> -1
str = sr.ReadLine()
If str.ToLower.IndexOf("test") > 0 Then
str = str.Replace(LCase("TEST"), LCase("xxx"))
NumReplaced += 1
EndIf

sw.Write(str)

Loop

sw.Close()
Fs.Close()



I used to rock and roll every night and party every day. Then it was every other day. Now I'm lucky if I can find 30 minutes a week in which to get funky. - Homer Simpson

Arrrr, mateys! Ye needs ta be preparin' yerselves fer Talk Like a Pirate Day!
 
This should do what you need:

NB ListBoxes added to display results


Code:
Imports System.IO
Imports System.Text.RegularExpressions

Public Class Form1

	Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

		ListBox1.Items.Clear()
		ListBox2.Items.Clear()

		Dim rx As New Regex("TEST", RegexOptions.IgnoreCase)
		Dim filename As String = My.Computer.FileSystem.SpecialDirectories.MyDocuments + "\Rubbish1a.txt"
		Dim sr As New StreamReader(filename)
		Dim source() As String = sr.ReadToEnd.Replace(Environment.NewLine, Chr(13)).Split(Chr(13).ToString.ToCharArray)
		ListBox2.Items.AddRange(source)
		sr.Close()
		Dim Changes As New List(Of Integer)
		For a As Integer = 0 To source.Length - 1
			If rx.IsMatch(source(a)) Then
				source(a) = rx.Replace(source(a), "xxx")
				Changes.Add(a + 1)
			End If
		Next
		Dim sw As New StreamWriter(filename)
		sw.Write(String.Join(Environment.NewLine, source))
		sw.Close()
		ListBox1.DataSource = Changes
		ListBox2.Items.AddRange(source)

	End Sub
End Class


Hope this helps.

[vampire][bat]
 
thanks earthandfire.
..this is pretty much the way it has to be done. 1st loop through the whole file and note where the changes will be made - then re-write the entire file.
thanks again

 
You can do it one line at a time, but unless the filesize is absolutely massive, then doing it in a single run is probably quicker.

The other problem with wrtiting out a line at a time is that you would need to write to a temporary file whilst processing, then when done, delete the original and rename the temporary file to the name of the original.


Hope this helps.

[vampire][bat]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top