Вопрос

I am trying to write my contents of my array to a file. Its an array as a structure. I seem to be having an issue. I can't seem to read the file after it has been written. The app freezes up and if I check to see if my txt file has any info in it, it locks up as well.

    Option Strict On
    Option Explicit On
    Option Infer Off

Public Class Form1
Structure Person
    Public strName As String
    Public dblHeight As Double
    Public dblWeight As Double
End Structure
Private peopleDescription(49) As Person

Dim count As Integer = 0

Private Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click

    If count <= 49 Then
        peopleDescription(count).strName = txtName.Text
        Double.TryParse(txtHeight.Text, peopleDescription(count).dblHeight)
        Double.TryParse(txtWeight.Text, peopleDescription(count).dblWeight)

        count += 1
    End If

    txtName.Text = String.Empty
    txtHeight.Text = String.Empty
    txtWeight.Text = String.Empty

    txtName.Focus()

End Sub

Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
    Dim outFile As IO.StreamWriter
    Dim intC As Integer

    outFile = IO.File.AppendText("persons.txt")

    Do While intC < count
        outFile.WriteLine(peopleDescription(intC))
    Loop

    outFile.Close()

End Sub

Private Sub btnRead_Click(sender As Object, e As EventArgs) Handles btnRead.Click
    Dim inFile As IO.StreamReader
    Dim strInfo As String

    If IO.File.Exists("persons.txt") Then
        inFile = IO.File.OpenText("persons.txt")
        Do Until inFile.Peek = -1
            strInfo = inFile.ReadLine
        Loop
        inFile.Close()
        lblMessage.Text = strInfo

    Else
        MessageBox.Show("Can't find the persons.txt file", "Person Data", MessageBoxButtons.OK, MessageBoxIcon.Information)

    End If

End Sub
End Class

I don't know what I am missing. If anyone can help I would appreciate it.

Это было полезно?

Решение

You fail to initialize intC before starting the while loop, and you're not incrementing it within the loop, so it never changes to exit it (presuming it gets inside the loop in the first place), which would make it seem to "lock up".

Set it to a starting value first, before you use it.

Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
    Dim outFile As IO.StreamWriter
    Dim intC As Integer = 0

    outFile = IO.File.AppendText("persons.txt")

    Do While intC < count
        outFile.WriteLine(peopleDescription(intC))
        intC += 1 
    Loop

    outFile.Close()
End Sub
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top