text files

  • Thread starter Thread starter herewegoagain
  • Start date Start date
H

herewegoagain

Guest
Hi all...
I am looking for an online tutorial or code sample that will allow me to edit a text file within a vb.net program. Such as if the line begins with "MBS" then that line would get deleted? Can anyone help?
 
Well, there is a basic tutorial on EliteVB about reading files. I suggest you read that tutorial,
as well as reading the MSDN that came with your VS.NET. Look
up StreamReader and StreamWriter to learn how to
read and write text files.

There are basically two ways to do what you want. You could either:

1) open two streams simultaneously (one reading your source file,
one writing to a temp file), and reading line-by-line through the
source file, while writing to the temp file if the line doesnt start
with MBS

2) read the lines into an array, and just loop through the array and overwrite the file with no temp files needed.

The following code does the latter:
Code:
        Open the file you want
        Dim sr As IO.StreamReader = New IO.StreamReader( _
                            New IO.FileStream("c:\somefile.txt", _
                                              IO.FileMode.Open))

        Read in the entire file, close the file
        Dim strFile As String
        strFile = sr.ReadToEnd()
        sr.Close()

        Split it into its individual lines
        Dim strSplit() As String
        strSplit = strFile.Split(ControlChars.Lf)

        Open the file for writing, clearing it
        Dim sw As IO.StreamWriter = New IO.StreamWriter( _
                            New IO.FileStream("c:\somefile.txt", _
                            IO.FileMode.Create))

        Set the newline character to a LineFeed alone (because
        the CarriageReturn is left over from the old file)
        sw.NewLine = ControlChars.Lf

        Loop through the array of lines and write to the
        temp file -- if it starts with MBS, dont write
        Dim i As Integer
        For i = 0 To strSplit.GetUpperBound(0)
            If Not strSplit(i).StartsWith("MBS") Then
                sw.WriteLine(strSplit(i))
            End If
        Next

        Close the file
        sw.Close()
 
Thank you and one more thing

Is it possible with this code where it says:
For i = 0 To strSplit.GetUpperBound(0)
If Not strSplit(i).StartsWith("MBS") Then
sw.WriteLine(strSplit(i))
End If
that it could also be if it starts with "MBS" and ends with "sbm"
 
Of course, just replace

If Not strSplit(i).StartsWith("MBS") Then

with

If (Not strSplit(i).StartsWith("MBS")) Or (strSplit(i).StartsWith("MBS") And strSplit(i).EndsWith("sbm")) Then
 

Similar threads

S
Replies
0
Views
57
sva0008
S
R
Replies
0
Views
370
RaviKantTiwari
R
A
Replies
0
Views
598
Antoine Besnard
A
Back
Top