English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

hello everyone i just wanted to know how can i modify a text file once i opened it and searched trough it and arrived at a point where the search returned something , i want to remove that line EG :


Do While stream_reader.Peek() > -1


nome_read = stream_reader.ReadLine()
If nome_read = nome Then
"Here I should remove the current line from the text file"
End If



lista_utenti.AppendText(nome & vbNewLine)


Loop

thx in advance

2007-04-27 07:06:43 · 1 answers · asked by cor_sibu 2 in Computers & Internet Programming & Design

1 answers

A streamReader can only read, use a streamWritter to write to a file...

To edit on the fly use both a streamReader and StreamWritter.
As each line is read test it for a match then if the line is not to be excluded copy it by writting into a temp file via the streamWritter.

Once you have read the entire file close bot the reader and writter streams then using the file object copy the editied file into the original. You can either delete the original file first and rename the tempfile as the original or overwrite the the original file with the tempfile as I have done.

Dim sr As System.IO.StreamReader
Dim sw As System.IO.StreamWriter
Dim txt, nome, origFile, tempFile As String
Dim overWriteOrigFile As Boolean = True

origFile = "C:\myTextFile.txt"
tempFile = "C:\myTemp.txt"

sr = System.IO.File.OpenText(origFile)

If System.IO.File.Exists(tempFile) Then
System.IO.File.Delete(tempFile)
End If
sw = System.IO.File.CreateText(tempFile)
nome = "Your Text to exclude on a match goes here"

Do While sr.Peek > -1
txt = sr.ReadLine
If txt = nome Then
'a match has been found delet this line by not
'writting it to duplicate file
Else
'copy the current line held in txt into duplicate file
sw.WriteLine(txt)
End If
Loop
'close both files
sr.Close()
sw.Close()
'Over write the temp file into the original file
System.IO.File.Copy(tempFile, origFile, overWriteOrigFile)

2007-04-27 09:34:31 · answer #1 · answered by MarkG 7 · 0 0

fedest.com, questions and answers