473,396 Members | 2,113 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

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
Mar 24 '08 #1
10 1105
Frinavale
9,735 Expert Mod 8TB
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
Mar 24 '08 #2
balabaster
797 Expert 512MB
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.
Mar 24 '08 #3
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:



Expand|Select|Wrap|Line Numbers
  1.  
  2.  Dim FILE_NAME As String = "C:\sample.txt"
  3.  
  4.  
  5.         Dim LineIn As String
  6.  
  7.         If File.Exists(FILE_NAME) = True Then
  8.  
  9.             ' Open and read my file 
  10.  
  11.             oRead = File.OpenText(FILE_NAME)
  12.             While oRead.Peek <> -1
  13.                 LineIn = oRead.ReadLine()
  14.  
  15.  
  16. 'If the line found matches the ID number the user entered
  17.  
  18.                 If LineIn = membersearch.Text Then 
  19.  
  20. 'HERE IS WHERE I WANT TO CHANGE fields
  21.  
  22.                     oRead.Close()
  23.  
  24.  
  25. ' Gets messy after
  26.  
  27.                     MsgBox(LineIn & " Found.")
  28.  
  29.                     ' Write to an existing file 
  30.                     oWrite = File.AppendText(FILE_NAME)
  31.  
  32. 'wanted then these lines to write within that record
  33.  
  34.                     oWrite.WriteLine(changetime.Text)
  35.                     oWrite.WriteLine(changelevel.Text)
  36.                     oWrite.WriteLine("---------")
  37.                     oWrite.Flush()
  38.                     oWrite.Close()
  39.                     Exit While
  40.                 End If
  41.  
  42.  
  43.  
Mar 24 '08 #4
Frinavale
9,735 Expert Mod 8TB
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.
Mar 24 '08 #5
ok thanks ill give it a go
Mar 24 '08 #6
balabaster
797 Expert 512MB
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:
Expand|Select|Wrap|Line Numbers
  1. Function InitDataStructure() As DataTable
  2.         Dim Data As New DataTable
  3.         Dim oKeyCol As New DataColumn("DataKey", GetType(Integer))
  4.         oKeyCol.AutoIncrement = True
  5.         oKeyCol.Unique = True
  6.         Data.Columns.Add(oKeyCol)
  7.         Data.Columns.Add(New DataColumn("Field1", GetType(String)))
  8.         Data.Columns.Add(New DataColumn("Field2", GetType(String)))
  9.         Data.Columns.Add(New DataColumn("Field3", GetType(String)))
  10.         Data.Columns.Add(New DataColumn("Field4", GetType(String)))
  11.         Dim oPrimaryKey() As DataColumn = {Data.Columns("DataKey")}
  12.         Data.PrimaryKey = oPrimaryKey
  13.         Return Data
  14. End Function
  15.  
  16. Function WriteDataToDisk(ByVal Data As DataTable, ByVal FileName As String) As Boolean
  17.         Dim sOut As String = ""
  18.         For iRow As Integer = 0 To Data.Rows.Count - 1
  19.             For iCol As Integer = 0 To Data.Columns.Count - 1
  20.                 sOut &= Data.Rows(iRow).Item(iCol) & ControlChars.CrLf
  21.             Next
  22.             If Not iRow = Data.Rows.Count - 1 Then
  23.                 sOut &= "------------------" & ControlChars.CrLf
  24.             End If
  25.         Next
  26.         System.IO.File.WriteAllText(FileName, sOut)
  27. End Function
  28.  
  29. Function ReadDataFromDisk(ByVal FileName As String) As DataTable
  30.         Dim oTable As DataTable = InitDataStructure()
  31.         Dim sLines() As String = System.IO.File.ReadAllLines(FileName)
  32.         Dim oData As New ArrayList
  33.         For i As Integer = 0 To sLines.Length - 1
  34.             If Not (sLines(i).StartsWith("-")) Then
  35.                 oData.Add(sLines(i))
  36.             End If
  37.             If (sLines(i).StartsWith("-")) Or (i = sLines.Length - 1) Then
  38.                 oTable.Rows.Add(oData.ToArray)
  39.                 oData.Clear()
  40.             End If
  41.         Next
  42.         Return oTable
  43. End Function
  44.  
  45. Sub Main()
  46.         Dim DataFolder As String = System.Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)
  47.         Dim DataFile As String = DataFolder & "\TestDB.txt"
  48.         Dim oDT As DataTable = ReadDataFromDisk(DataFile)
  49.  
  50.         Dim iCurrentSelection As Integer = 2 'Currently selected record is 2
  51.         oDT.Rows(iCurrentSelection).Item("Field1") = "MyTestChange" 'Here is my change to the record
  52.  
  53.         If WriteDataToDisk(oDT, DataFile) Then MsgBox("Update successfully saved.") 'Save the data back to my datafile - or another datafile if you choose...
  54.  
  55. End Sub
Adding a new record to your database would be as simple as:
Expand|Select|Wrap|Line Numbers
  1. Dim NextRec As Integer = oDT.Rows(oDT.Rows.Count - 1).Item(0) + 1
  2. Dim NewData() As String = {NextRec, "Test1", "Test2", "Test3", "Test4"}
  3. oDT.Rows.Add(NewData)
And deleting a record from your database would be as simple as:
Expand|Select|Wrap|Line Numbers
  1. Dim iKeyToDelete As Integer = 4
  2. oDT.Rows.Find(iKeyToDelete).Delete()
Sorting your records is also a piece of cake:
Expand|Select|Wrap|Line Numbers
  1. oDT.DefaultView.Sort = "Field2 Desc" 'for Field2 descending
  2. 'Or
  3. 'oDT.DefaultView.Sort = "DataKey Asc" 'for datakey ascending
Mar 24 '08 #7
Frinavale
9,735 Expert Mod 8TB
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
Mar 24 '08 #8
balabaster
797 Expert 512MB
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)
Mar 24 '08 #9
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.


Expand|Select|Wrap|Line Numbers
  1.  
  2.  
  3.  
  4.         reader = File.OpenText("C:\sample.txt")
  5.  
  6.         aryText = (reader.ReadToEnd.ToCharArray())
  7.  
  8.         reader.Close()
  9.  
  10.         MsgBox(aryText)
  11.  
  12.  

Now the whole file is in an array how do i search and ammend ?
Mar 25 '08 #10
balabaster
797 Expert 512MB
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
Expand|Select|Wrap|Line Numbers
  1. Dim iKeyToChange As Integer = 3
  2. Dim oDR As DataRow = oDT.Rows.Find(iKeyToChange)
  3. oDR.Item("Field4") = "This is my new test value"
  4. 'Don't forget to write the data table back to the file when we're done making changes
  5. WriteDataToDisk(oDT, DataFile)
Mar 25 '08 #11

Sign in to post your reply or Sign up for a free account.

Similar topics

16
by: nephish | last post by:
Hey there, kinda newbie question here. i know how to read the lines of a txt file. i know how to write a txt file. but how do i overwrite a line value with another value ? i mean, how do go...
4
by: Tatu Portin | last post by:
Is there any convenient way to program text-handling routines in C? For example, I have a text file and I want to remove every other line, and then write the output. Or should I read tutorials...
2
by: Todd_M | last post by:
I was wondering what anyone might suggest as "best practice" patterns for streaming out fixed formatted text files with C#? Let's say we get our data in a dataset table and we need to iterate over...
9
by: anachronic_individual | last post by:
Hi all, Is there a standard library function to insert an array of characters at a particular point in a text stream without overwriting the existing content, such that the following data in...
29
by: list | last post by:
Hi folks, I am new to Googlegroups. I asked my questions at other forums, since now. I have an important question: I have to check files if they are binary(.bmp, .avi, .jpg) or text(.txt,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.