How to insert lines of text into an existing text file?

G

Guest

Currently i am using the below coding to create a text file and write something on it.

Dim wfile As New System.IO.StreamWriter("c:\test.txt"
wfile.WriteLine("Hello" & vbcrlf & "Are" & vbcrlf & "You"
wfile.Close(

The text file content should be like thi

Hell
Ar
Yo

What if i want to insert "How" into the text file to modify the text file become like this.

Hell
Ho
Ar
Yo

Anyone can provide the coding on how to get the specific line in a text file and insert lines of text into the text file?Any help is greatly appreciated... Thanks..
 
W

William Ryan eMVP

Dim s as String = "Hello" & ControlChars.CrLf & "Are" & ControlChars.Crlf &
"You"

s.Insert(5, "How")
MJ said:
Currently i am using the below coding to create a text file and write something on it..

Dim wfile As New System.IO.StreamWriter("c:\test.txt")
wfile.WriteLine("Hello" & vbcrlf & "Are" & vbcrlf & "You")
wfile.Close()

The text file content should be like this

Hello
Are
You

What if i want to insert "How" into the text file to modify the text file become like this..


Hello
How
Are
You

Anyone can provide the coding on how to get the specific line in a text
file and insert lines of text into the text file?Any help is greatly
appreciated... Thanks..
 
J

Jon Skeet [C# MVP]

MJ said:
Anyone can provide the coding on how to get the specific line in a
text file and insert lines of text into the text file?Any help is
greatly appreciated... Thanks..

You need to rewrite the whole file, basically. One way which doesn't
take up too much memory is to read from the file and write to a
temporary file, then delete the old file and rename the new one
appropriately. Line insertions are achieved by reading/writing some
lines, then writing the new lines, then reading/writing the rest of the
lines.
 
C

Cor

Hi MJ,

Looking it over and looking at the other messages than I think you can maybe
also use the.

mystring.replace(" ", vbcrlf)

And to make our C# friends happy.

I did a test this week which I have showed in the languages.vb newsgroup.

This is the fastest replace in my test and with a long string it can be more
than 100 times faster than the Vb.microsoft string function. (This in
oposite from the indexoff where the vb.microsoft function were in my tests
twice as fast with a string and twice as slow with a character).

Cor
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top