Guest herewegoagain Posted November 14, 2002 Posted November 14, 2002 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? Quote
*Experts* Volte Posted November 17, 2002 *Experts* Posted November 17, 2002 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 doesn't 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: '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, don't 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() Quote
Guest herewegoagain Posted November 18, 2002 Posted November 18, 2002 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" Quote
wyrd Posted November 18, 2002 Posted November 18, 2002 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 Quote Gamer extraordinaire. Programmer wannabe.
Guest herewegoagain Posted November 18, 2002 Posted November 18, 2002 This group rocks..... Thank you...... Quote
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.