1 Replies - 4054 Views - Last Post: 07 September 2010 - 01:51 AM Rate Topic: -----

#1 south73paw  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 88
  • Joined: 06-October 08

Save data to random access files

Posted 06 September 2010 - 10:14 PM

Hi, how do you save data stored in an array of records (structure) to a text file using StreamWriter? I currently have

    Private Sub btnSaveToFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSaveToFile.Click

        Dim sw As New StreamWriter(New FileStream("EmployeeDetails.txt", FileMode.Create, FileAccess.Write))

        For Each record As EmployeeType In employees
            sw.Write(record.ID & ",")
            sw.Write(record.FirstName & ",")
            sw.WriteLine(record.Salary)
        Next

        sw.Close()

    End Sub


but it doesn't work. My array is fixed and currently has 3 elements (for testing purposes). If I enter two records and add these to the structure I get the following data saved to the text file:

123,helen,66000
879,john,89975
0,,0


How do I stop unused elements of the array being included when writing to file? Should I use a dynamic array instead and if yes, how do you use dynamic arrays with structures?

Thanks
:turned:

Is This A Good Question/Topic? 0
  • +

Replies To: Save data to random access files

#2 motcom  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 290
  • View blog
  • Posts: 1,371
  • Joined: 16-June 08

Re: Save data to random access files

Posted 07 September 2010 - 01:51 AM

Hi,

What you are doing is ok i guess, not at my dev pc but also not so sure about serialization with structures. (basically the idea is that you can dump the Structure to a file and read it again, just as you are doing, however with serialization it should be easier to read and write.)

Second thing is you said you added 2 records, however it did write 3, that means (as you use "for each") that there are in fact 3, so maybe somewhere in your code you do add another record... just check that
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1