Read text file after change text " text1 " to " text2" 

Example text file name hhh.txt have content
sdasdsa
ádsaewf
dsasa asdsa text1 asdksls text1 as

+>>>> hhh.txt
sdasdsa
ádsaewf
dsasa asdsa text2 asdksls text2 as
Thk :)

Dani AI

Generated

wanted a reliable way to change every occurrence of "text1" to "text2" in hhh.txt; earlier posts point out parsing and simple reads, but they skip a few practical pitfalls (encoding, locks, atomic writes, watcher noise). Below are concise, practical patterns to use in VB.NET that address those gaps and are safe to run in real apps.

A safe one‑time replace: open the file for shared read so readers/writers don't clash, detect encoding, do the replace in memory, write to a temp file, then atomically swap with a backup. This preserves data if something fails during the write.

' one-off safe replace (VB.NET)
Dim path As String = "D:\hhh.txt"
Dim temp As String = path & ".tmp"
Dim backup As String = path & ".bak"

Dim text As String
Using fs As New IO.FileStream(path, IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.ReadWrite)
    Using sr As New IO.StreamReader(fs, System.Text.Encoding.UTF8, True)
        text = sr.ReadToEnd()
    End Using
End Using

text = text.Replace("text1", "text2")

IO.File.WriteAllText(temp, text, System.Text.Encoding.UTF8)
IO.File.Replace(temp, path, backup)

For continuous monitoring use a FileSystemWatcher plus a short debounce (timer) so multiple rapid Changed events collapse into one read/replace. Ensure the watcher is disabled or the event ignored while your code writes the file (otherwise your write will retrigger the watcher). Also track last processed timestamp to avoid reprocessing the same change.

Cautions and gotchas: handle encoding (the sample file contains accented characters), catch IOExceptions from locked files and retry with an exponential backoff, keep a backup (.bak) before replacing, and prefer whole‑word or regex replacements if you must avoid partial matches. Finally, credit to and for prompting the file‑read and event ideas noted above; the patterns here focus on robustness for real deployments.

Recommended Answers

All 3 Replies

what code have you got, and what part doesn't work right?

You're best bet is to look at the VB samples - Language Samples - String Methods Sample program and get some ideas about how to use the string functions.

There are two methods I use to process text - an array or a buffer.

1) In VB, you can use String.Split to parse it into an array based on a delimiter (default is CrLf). The advantage here is when the text is structured you can get to the part you need using an index number. In you sample, the text you need is in 3rd line, positions 3 and 5. You can get 3rd line with str1=array[2], then parse line by spaces -- Dim myArray() As String = Split(str1, " ") -- and get the 3rd and 5th words -- str2 = myArray[2]; str3 = myArray[4]. This works great if the text is formatted the same every time. Not so good if the format varies.

2) The other option is to read the whole file into a string variable and scan it for the substring 'text1' using Sample.Substring() or Sample.IndexOf().
Tip: Avoid using a temp variable repeatedly to parse strings.

[Note: In VB.Net, StringBuilder can be used to load a long string of text into a buffer and read, modify, replace or delete substrings within the string. It provides lots of flexibility without the performance hit you get with using string functions to read and write to string variables.]

How are you monitoring the file for changes? Do you have an event sink that checks if the file has changed? Do you check the modified date-time at intervals? Do you have a process that fires an event? I'll assume you have a trigger to read the file. If not, you may want to look at the FileSystem samples. You can use the FileSystem object to check the modified date.

Dim fso as new FileSystemObject
Set fso = Nothing
Set fso = New FileSystemObject
strFileName = "D:\Deepak.txt"
fso.OpenTextFile (strFileName)
Set ts = fso.OpenTextFile(strFileName)
While Not ts.AtEndOfStream
    strCurrentLineText = ""
    strCurrentLineText = ts.ReadLine
    Debug.Print strCurrentLineText
Wend
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.