Replace Characters In Text File

  • Thread starter Thread starter Derek Hart
  • Start date Start date
D

Derek Hart

Using VB.NET, I wish to open a text file that will have paragraph marks
throughout it. To replace them, I can probably use the Replace command and
replace vbcrlf. But can somebody give me sample code using the StreamWriter
object, if that is the best way, to open the text file, replace the
paragraph marks, and save those changes back to the text file. I am not
sure if I should read in the text file line by line, do the replacing, save
the whole thing to a variable, and then recreate the text file. Please send
code if you have a way to do this.

Thank You,
Derek Hart
 
Hi Derek,

I think we also need to use the StreamReader to read the file,because the
StreamWriter did not provide the read function.
Imports System.IO
Module Module1
Sub Main()
Dim Fs As FileStream = New FileStream("c:\Edit1.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(vbCrLf, "^")
Fs.Position = 0
Fs.SetLength(str.Length)
'because the vbCrLf will take two bytes, but the ^ just one byte, so we
need to adjust the lenghth and that is why we need to read all the data
into a string.
sw.Write(str)
sw.Flush()
sw.Close()
Fs.Close()
End Sub
End Module


Best regards,

Peter Huang
Microsoft Online Partner Support

Get Secure! - www.microsoft.com/security
This posting is provided "AS IS" with no warranties, and confers no rights.
 
Back
Top