Text file Handling

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • insomnia
    New Member
    • Mar 2008
    • 11

    Text file Handling

    Hi there, need to be able to create a text file that stores information like so :
    this i have managed with a stream writer/append

    1
    aaaa
    bbbbb
    ccccccc
    dddddddd
    ------------------
    2
    aaaa
    bbbbb
    cccccc
    dddddddd

    My problem is now i have to "Edit" an individual line within the text file.
    e.g. The user enters number "2" in to a text box to verify which record they wish to access. (the streamreader needs to locate that record) The user then needs to change the entry details for "bbbbb" to "xxxxx" for that record only.

    Any ideas on how to search a file for the identification number e.g. 2 and then modify the 2nd line down within that record.

    thanks in advance
  • Frinavale
    Recognized Expert Expert
    • Oct 2006
    • 9749

    #2
    Originally posted by insomnia
    Hi there, need to be able to create a text file that stores information like so :
    this i have managed with a stream writer/append

    1
    aaaa
    bbbbb
    ccccccc
    dddddddd
    ------------------
    2
    aaaa
    bbbbb
    cccccc
    dddddddd

    My problem is now i have to "Edit" an individual line within the text file.
    e.g. The user enters number "2" in to a text box to verify which record they wish to access. (the streamreader needs to locate that record) The user then needs to change the entry details for "bbbbb" to "xxxxx" for that record only.

    Any ideas on how to search a file for the identification number e.g. 2 and then modify the 2nd line down within that record.

    thanks in advance

    Have you checked MSDN?
    There's an article on How To Read Text From A File. It tells you how to grab the lines from the text file...

    One possible solution would be to take all of the lines from the text file and add them to an ArrayList. Then, depending on what the user has entered, edit that String (at that index array)...after your finished editing, over write the text file with the contents of the ArrayList....

    There are many other ways to solve this problem.
    Give it a try and then get back to us if you get stuck on something more specific.

    -Frinny

    Comment

    • balabaster
      Recognized Expert Contributor
      • Mar 2007
      • 798

      #3
      Are we talking a flat file storage format of a DataTable?

      I'd probably create a DataTable of x columns, where the first is the primary key and the remaining items (before the -------) are the other fields. Then I'd create a DataRow of the same amount of columns parsing each item (before the -------) into one of the fields in the DataRow. As each DataRow is completed, I'd add it to the DataTable. Once all of the data is in the DataTable it's far easier to query and thus making further coding simpler and more efficient as you are now querying memory instead of relaying to/from disk for each read.

      My save would then iterate the DataTable writing each DataRow back to the file...you could choose just to write the rows/fields that have changed, or you could write the whole file... depending on the file size and how much data has changed depends on which method you're likely to choose. If the amount of data is small or a large portion of the data changes each time, then it's mostly likely more efficient to write the whole table back to the file, otherwise you may wish to just write the changed fields.

      Just my humble 2 cents... if this is purely a file read/write exercise, then I'm most likely complicating the issue for you - even though from a code standpoint it's far more elegant/efficient.

      Comment

      • insomnia
        New Member
        • Mar 2008
        • 11

        #4
        Originally posted by Frinavale
        One possible solution would be to take all of the lines from the text file and add them to an ArrayList. Then, depending on what the user has entered, edit that String (at that index array)...after your finished editing, over write the text file with the contents of the ArrayList....
        -Frinny
        This was the idea i had in mind, grabbing the lines from the text file and putting them in to an array.

        So do you recommend reading the entire text file and turning it in to an arraylist?



        Thanks Balablaster but yes it is a simple read/write/ammend task.
        im trying to make a very simple mini database to store records using a text file



        This is what i was trying to do before, although it now clearly rubbish, I will try and give the arraylist idea a go:



        [CODE=vbnet]

        Dim FILE_NAME As String = "C:\sample. txt"


        Dim LineIn As String

        If File.Exists(FIL E_NAME) = True Then

        ' Open and read my file

        oRead = File.OpenText(F ILE_NAME)
        While oRead.Peek <> -1
        LineIn = oRead.ReadLine( )


        'If the line found matches the ID number the user entered

        If LineIn = membersearch.Te xt Then

        'HERE IS WHERE I WANT TO CHANGE fields

        oRead.Close()


        ' Gets messy after

        MsgBox(LineIn & " Found.")

        ' Write to an existing file
        oWrite = File.AppendText (FILE_NAME)

        'wanted then these lines to write within that record

        oWrite.WriteLin e(changetime.Te xt)
        oWrite.WriteLin e(changelevel.T ext)
        oWrite.WriteLin e("---------")
        oWrite.Flush()
        oWrite.Close()
        Exit While
        End If


        [/CODE]

        Comment

        • Frinavale
          Recognized Expert Expert
          • Oct 2006
          • 9749

          #5
          Make one function for reading the file into your ArrayList.

          Once the file's read into the array, then make the changes to the strings at whatever spot they should be modified.

          After this is finished (or if you fail), call another function that opens the file again and overwrites it with the modified data.

          Comment

          • insomnia
            New Member
            • Mar 2008
            • 11

            #6
            ok thanks ill give it a go

            Comment

            • balabaster
              Recognized Expert Contributor
              • Mar 2007
              • 798

              #7
              Not sure if this is any use...it's a different method than the one you're using - it may provide more flexibility down the road:
              Code:
              Function InitDataStructure() As DataTable
              		Dim Data As New DataTable
              		Dim oKeyCol As New DataColumn("DataKey", GetType(Integer))
              		oKeyCol.AutoIncrement = True
              		oKeyCol.Unique = True
              		Data.Columns.Add(oKeyCol)
              		Data.Columns.Add(New DataColumn("Field1", GetType(String)))
              		Data.Columns.Add(New DataColumn("Field2", GetType(String)))
              		Data.Columns.Add(New DataColumn("Field3", GetType(String)))
              		Data.Columns.Add(New DataColumn("Field4", GetType(String)))
              		Dim oPrimaryKey() As DataColumn = {Data.Columns("DataKey")}
              		Data.PrimaryKey = oPrimaryKey
              		Return Data
              End Function
               
              Function WriteDataToDisk(ByVal Data As DataTable, ByVal FileName As String) As Boolean
              		Dim sOut As String = ""
              		For iRow As Integer = 0 To Data.Rows.Count - 1
              			For iCol As Integer = 0 To Data.Columns.Count - 1
              				sOut &= Data.Rows(iRow).Item(iCol) & ControlChars.CrLf
              			Next
              			If Not iRow = Data.Rows.Count - 1 Then
              				sOut &= "------------------" & ControlChars.CrLf
              			End If
              		Next
              		System.IO.File.WriteAllText(FileName, sOut)
              End Function
               
              Function ReadDataFromDisk(ByVal FileName As String) As DataTable
              		Dim oTable As DataTable = InitDataStructure()
              		Dim sLines() As String = System.IO.File.ReadAllLines(FileName)
              		Dim oData As New ArrayList
              		For i As Integer = 0 To sLines.Length - 1
              			If Not (sLines(i).StartsWith("-")) Then
              				oData.Add(sLines(i))
              			End If
              			If (sLines(i).StartsWith("-")) Or (i = sLines.Length - 1) Then
              				oTable.Rows.Add(oData.ToArray)
              				oData.Clear()
              			End If
              		Next
              		Return oTable
              End Function
               
              Sub Main()
              		Dim DataFolder As String = System.Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)
              		Dim DataFile As String = DataFolder & "\TestDB.txt"
              		Dim oDT As DataTable = ReadDataFromDisk(DataFile)
               
              		Dim iCurrentSelection As Integer = 2 'Currently selected record is 2
              		oDT.Rows(iCurrentSelection).Item("Field1") = "MyTestChange" 'Here is my change to the record
               
              		If WriteDataToDisk(oDT, DataFile) Then MsgBox("Update successfully saved.") 'Save the data back to my datafile - or another datafile if you choose...
               
              End Sub
              Adding a new record to your database would be as simple as:
              Code:
              Dim NextRec As Integer = oDT.Rows(oDT.Rows.Count - 1).Item(0) + 1
              Dim NewData() As String = {NextRec, "Test1", "Test2", "Test3", "Test4"}
              oDT.Rows.Add(NewData)
              And deleting a record from your database would be as simple as:
              Code:
              Dim iKeyToDelete As Integer = 4
              oDT.Rows.Find(iKeyToDelete).Delete()
              Sorting your records is also a piece of cake:
              Code:
              oDT.DefaultView.Sort = "Field2 Desc" 'for Field2 descending
              'Or
              'oDT.DefaultView.Sort = "DataKey Asc" 'for datakey ascending

              Comment

              • Frinavale
                Recognized Expert Expert
                • Oct 2006
                • 9749

                #8
                Originally posted by balabaster
                Not sure if this is any use...it's a different method than the one you're using - it may provide more flexibility down the road:
                ...
                I like your solution Balabaster :)
                I have a feeling it's a bit too complicated for what this OP is looking for but I'm sure that it will help other people who are looking for this type of solution :)

                -Frinny

                Comment

                • balabaster
                  Recognized Expert Contributor
                  • Mar 2007
                  • 798

                  #9
                  Originally posted by Frinavale
                  I like your solution Balabaster :)
                  I have a feeling it's a bit too complicated for what this OP is looking for but I'm sure that it will help other people who are looking for this type of solution :)

                  -Frinny
                  Thanks - I have a feeling it's a bit too complex too...

                  I wasn't going to post the code, but I thought I'd do it as an exercise to raise the point that there's usually more than one way to skin a cat and that sometimes a different approach will pay dividends when it comes to extending the software.

                  Lots of programmers get blinkered in and spend tonnes of time trying to code around issues that could be avoided with some extra forethought. A reminder to think outside the box that is the design-brief ;o)

                  Comment

                  • insomnia
                    New Member
                    • Mar 2008
                    • 11

                    #10
                    Balablaster thanks for that.

                    And how would you ammend an existing record in your data base ?

                    The problem i am having with my data base at the moment is.

                    I cant AMMEND an existing record within the text file.
                    Ive just started looking at arrays as suggested before, but i am quite a novice.


                    Code:
                    
                    
                            reader = File.OpenText("C:\sample.txt")
                    
                            aryText = (reader.ReadToEnd.ToCharArray())
                    
                            reader.Close()
                    
                            MsgBox(aryText)

                    Now the whole file is in an array how do i search and ammend ?

                    Comment

                    • balabaster
                      Recognized Expert Contributor
                      • Mar 2007
                      • 798

                      #11
                      Originally posted by insomnia
                      Balablaster thanks for that.

                      And how would you ammend an existing record in your data base ?
                      Lines 50/51 of my original code show you how to change a record - the code below should be easier to follow - this is how you would edit the field called "Field4" in the record having the primary key of 3
                      Code:
                      Dim iKeyToChange As Integer = 3
                      Dim oDR As DataRow = oDT.Rows.Find(iKeyToChange)
                      oDR.Item("Field4") = "This is my new test value"
                      'Don't forget to write the data table back to the file when we're done making changes
                      WriteDataToDisk(oDT, DataFile)

                      Comment

                      Working...