Results 1 to 4 of 4

Thread: Appending Text to a File in VB .NET

  1. #1

    Thread Starter
    Junior Member
    Join Date
    Jun 2005
    Posts
    26

    Unhappy Appending Text to a File in VB .NET

    I want to be able to append text in the middle of a text file instead of at the end. What the below code does it searches for the [BrandIcons1] line, then it should immediately append text directly below [BrandIcons1]. But it appends at the end of the file.

    I’m using vb.net 2003. There’s gotta be a way to do this.

    Here’s what I have so far:


    VB Code:
    1. Private Sub btnWriteToFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnWriteToFile.Click
    2.         Dim oFile As System.IO.File
    3.         Dim oRead As System.IO.StreamReader
    4.         Dim oWrite As System.IO.StreamWriter
    5.         Dim FILE_NAME As String = "C:\Program Files\WCS\Mobility\Config\mobility1.ini"
    6.         Dim FILE_COPY As String = "C:\Program Files\WCS\Mobility\Config\mobility2.ini"
    7.         Dim LineIn As String
    8.  
    9.         If oFile.Exists(FILE_NAME) = True Then
    10.             oFile.Copy(FILE_NAME, FILE_COPY, True)
    11.             '
    12.             ' Open and read an exisiting file
    13.             oRead = oFile.OpenText(FILE_NAME)
    14.             While oRead.Peek <> -1
    15.                 LineIn = oRead.ReadLine()
    16.                 If LineIn = "[BrandIcons1]" Then
    17.                     oRead.Close()
    18.  
    19.                     MsgBox(LineIn & " Found.")
    20.                     ' Write to an existing file
    21.                     oWrite = oFile.AppendText(FILE_NAME)
    22.  
    23.                     oWrite.WriteLine("[BrandIcons]")
    24.                     oWrite.WriteLine("BE18=as1.bmp")
    25.                     oWrite.WriteLine("BE01=bu4.bmp")
    26.                     oWrite.WriteLine("BE02=")
    27.                     oWrite.WriteLine("---------")
    28.                     oWrite.Flush()
    29.                     oWrite.Close()
    30.                     Exit While
    31.                 End If
    32.             End While
    33.             MsgBox("Done!")
    34.         Else
    35.             MsgBox("File Does Not Exist: " & vbCrLf _
    36.               & FILE_NAME)
    37.         End If
    38.         Me.Close() 'End the program and close the form
    39.     End Sub

    The file to append Mobility1.ini
    [MOBILITY]
    back drive=d
    standard header 1=Digital Matrix, Inc.
    standard header 2=Budweiser
    standard header 3=Holiday, CA
    Last Backup Drive=d
    dBev Compatibility=F
    Sell Items Not In Product List=T
    Auto Lost Placement Enabled=F
    Auto Lost Placement Days=365
    Use IBS Interface=F
    Use IBS For Survey=F
    Use IBS For WEARS=F
    IBS Application Path=
    IBS Window Title=IBS
    Expired License Popup Msg Enabled=T

    [BrandIcons1]
    <append text information here>

    [TCOMM]
    host name=w55511
    host ip=192.168.1.2
    host login=wcs
    host password=qjris
    RAS Entry=Mobility
    RAS phone number=555-1212
    RAS login=np
    RAS password=nkfl
    RAS timeout=120
    max tcomm number=99
    Any help would be appreciated.

  2. #2
    Fanatic Member
    Join Date
    May 2005
    Posts
    898

    Re: Appending Text to a File in VB .NET

    Hi joop (fellow dutchman?)

    I think you only have two choices.

    1> Read the entire file to memory and write it back to disk with the new text inserted.
    2> Create a tempfile with the new text in it and then replace the original.
    "so just keep in mind that fantasy is not the same as realtiy and make sure u remember that wii sports may be fun but u cant count on it as exercise ok cool bye" - HungarianHuman

  3. #3
    Hyperactive Member jonwondering's Avatar
    Join Date
    May 2005
    Posts
    311

    Re: Appending Text to a File in VB .NET

    When you open text with .AppendText(), it doesn't matter where you are located. The function will open the file and move to the location at the very end. You can solve the problem grilkip's way:

    Read in the file until you find whatever you need, then write the new information, and only then read in the rest of the original file.
    Once you have this new file, you can write it back replacing the old one.

  4. #4

    Thread Starter
    Junior Member
    Join Date
    Jun 2005
    Posts
    26

    Smile Re: Appending Text to a File in VB .NET

    Your idea worked!

    You can see the above mobility.ini file. There are four sections to the file.
    [MOBILITY]
    [TCOMM]
    [BrandIcons]
    [Wears Item Ranges]

    I needed to place the text information under [BrandIcons] and not disturb the other information of this file (mobility.ini).

    I extracted each line of the file and placed them in an array. Then copied each line back into another file, followed by the text lines I needed to be inserted, and then continued on copying lines of the text file.

    Here the code. It’s not a clean code, but it works:

    Code:
    Private Sub btnReadFileIntoMemory_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReadFileIntoMemory.Click
            'http://www.builderau.com.au/program/windows/0,39024644,20267367,00.htm
            'http://www.seattlecentral.org/faculty/ymoh/mic110vb/sequential_file.htm
            '
            Dim oFile As System.IO.File
            Dim oRead As System.IO.StreamReader
            Dim oWrite As System.IO.StreamWriter
            Dim FILE_NAME As String = "C:\Program Files\WCS\Mobility\Config\mobility.ini"
            Dim FILE_COPY As String = "C:\Program Files\WCS\Mobility\Config\mobility2.ini"
            Dim FILE_BACK As String = "C:\Program Files\WCS\Mobility\Config\mobility3.txt"
            Dim strMobility(20) As String 'The lower bound is always 0 so this array contains 11 elements numbered 0 through 10. 
            Dim strTCOMM(15) As String
            Dim strWearsItem(10) As String
            Dim LineIn As String
            Dim intMobility As Integer, intTCOMM As Integer, intWearsItems As Integer
            Dim intCounter As Integer, i As Integer
            Dim intLineCounter As Integer
            '
            ' Backup the file
            oFile.Copy(FILE_NAME, FILE_BACK, True)
            'Create a COPY of the file to Append
            oWrite = oFile.CreateText(FILE_COPY)
            oWrite.Flush()
            oWrite.Close()
            ' Open and read an exisiting file
            '
            '-------------- [MOBILITY] -------------------- 
            oRead = oFile.OpenText(FILE_NAME)
            intLineCounter = 0
            ' Read each line of a TEXT file into memory
            While oRead.Peek <> -1
                LineIn = oRead.ReadLine()
                intCounter = intCounter + 1
                If LineIn = "[MOBILITY]" Then
                    intLineCounter = intLineCounter + 1 ' Total number of line for [MOBILITY]
                    strMobility(0) = LineIn
                    For i = 1 To 20
                        intLineCounter = intLineCounter + 1
                        strMobility(i) = oRead.ReadLine()
                        If strMobility(i) = "" Then
                            Exit For
                        End If
                    Next
                End If
            End While
            oRead.Close()
            intCounter = -1
            intLineCounter = intLineCounter - 3
            ' Write to an exisiting existing file
            oWrite = oFile.AppendText(FILE_COPY)
            Do While intCounter <= intLineCounter
                intCounter = intCounter + 1
                oWrite.WriteLine(strMobility(intCounter))
            Loop
            oWrite.WriteLine("")
            oWrite.Flush()
            oWrite.Close()
            '
            '-------------- [TCOMM] -------------------- 
            oRead = oFile.OpenText(FILE_NAME)
            intLineCounter = 0
            ' Read each line of a TEXT file into memory
            While oRead.Peek <> -1
                LineIn = oRead.ReadLine()
                intCounter = intCounter + 1
                If LineIn = "[TCOMM]" Then
                    intLineCounter = intLineCounter + 1 ' Total number of line for [TCOMM]
                    strTCOMM(0) = LineIn
                    For i = 1 To 20
                        intLineCounter = intLineCounter + 1
                        strTCOMM(i) = oRead.ReadLine()
                        If strTCOMM(i) = "" Then
                            Exit For
                        End If
                    Next
                End If
            End While
            oRead.Close()
            intCounter = -1
            intLineCounter = intLineCounter - 3
            ' Write to an exisiting existing file
            oWrite = oFile.AppendText(FILE_COPY)
            Do While intCounter <= intLineCounter
                intCounter = intCounter + 1
                oWrite.WriteLine(strTCOMM(intCounter))
            Loop
            oWrite.WriteLine("")
            oWrite.Flush()
            oWrite.Close()
            '
            '-------------- [BrandIcons] -------------------- 
            ' Write to an exisiting existing file
            ' <append text information here>
            oWrite = oFile.AppendText(FILE_COPY)
            oWrite.WriteLine("[BrandIcons]")
            oWrite.WriteLine("BE18=as1.bmp")
            oWrite.WriteLine("BE01=bu4.bmp")
            oWrite.WriteLine("BE02=")
            oWrite.WriteLine("")
            oWrite.Close()
            '
            '-------------- [Wears Item Ranges] -------------------- 
            oRead = oFile.OpenText(FILE_NAME)
            intLineCounter = 0
            ' Read each line of a TEXT file into memory
            While oRead.Peek <> -1
                LineIn = oRead.ReadLine()
                intCounter = intCounter + 1
                If LineIn = "[Wears Item Ranges]" Then
                    intLineCounter = intLineCounter + 1 ' Total number of line for [WEARS]
                    strWearsItem(0) = LineIn
                    For i = 1 To 20
                        intLineCounter = intLineCounter + 1
                        strWearsItem(i) = oRead.ReadLine()
                        If strWearsItem(i) = "" Then
                            Exit For
                        End If
                    Next
                End If
            End While
            oRead.Close()
            intCounter = -1
            intLineCounter = intLineCounter - 3
            ' Write to an exisiting existing file
            oWrite = oFile.AppendText(FILE_COPY)
            Do While intCounter <= intLineCounter
                intCounter = intCounter + 1
                oWrite.WriteLine(strWearsItem(intCounter))
            Loop
            oWrite.WriteLine("")
            oWrite.Flush()
            oWrite.Close()
            'Copy the file back to mobility.ini
            oFile.Copy(FILE_COPY, FILE_NAME, True)
            'DONE!
            MsgBox("Done!")
            ' not a clean code but it works.
        End Sub
    Thanks for all your help.
    Last edited by joopdog; Jun 30th, 2005 at 02:07 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width