Сохранение структуры в двоичный файл - PullRequest
0 голосов
/ 05 февраля 2019

Я создаю приложение с помощью приложения Windows Forms в Visual Studio на языке vb.net.Мне нужна помощь в преобразовании структуры, которую я закодировал, в двоичный файл, который, по сути, сохраняет результаты пользователя.Я не очень хороший кодер, так что извините за плохой код.

Приведенный ниже код показывает, что я создал структуру с именем saveresults, и, нажав button1, он должен получить содержимое двоичного файла.и отредактируйте их, чтобы получить новый результат.Когда я запускаю код, кажется, что проблема в строке FileOpen(1, "/bin/debug/1.txt", OpenMode.Binary) в подпрограмме saveres.

Structure saveresults 'Structure for saving results
        Dim numright As Integer
        Dim numwrong As Integer
        Dim totalnum As Integer
End Structure
'Subroutine aimed at getting stats saved to a text file to eventually be displayed to the user

Sub saveres(saveresults As saveresults, correct As Boolean)
    saveresults.totalnum = saveresults.totalnum + 1
    'Determining the contents to be saved to the binary file
    If correct = True Then
        saveresults.numright = saveresults.numright + 1
    ElseIf correct = False Then
        saveresults.numwrong = saveresults.numwrong + 1
    End If
    FileOpen(1, "/bin/debug/1.txt", OpenMode.Binary)
    FilePut(1, saveresults)
    FileClose(1)

End Sub

'attempt at saving results to the binary file

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim correct = True
    Dim results As saveresults
    FileOpen(1, "/bin/debug/1.txt", OpenMode.Binary)
    FileGet(1, results)
    saveres(results, correct)
    FileClose(1)
End Sub

Любая помощь приветствуется.Спасибо.

Ответы [ 2 ]

0 голосов
/ 06 февраля 2019

Вы имеете в виду текстовые и двоичные файлы, как если бы они были одним и тем же.Они не.Текстовые файлы читаются человеком в Блокноте;бинарные файлы не являются.

Я не использовал методы, которые вы пытаетесь, начиная с VB 6. Используйте методы .Net System.IO.Чтобы использовать их, вам нужно добавить Imports System.IO в самый верх вашего файла кода.

Я разбил ваш код на вспомогательные элементы и функции, которые имеют одну цель.Чтение файла, запись файла, обновление данных и отображение данных.Это делает код более понятным.Если ваш код плохо себя ведет, его легче найти и исправить, если у метода есть только одна вещь.

Расположение файла в примере находится в том же каталоге, что и ваш файл .exe.Возможно /bin/Degug.

'A Form level variable to hold the data
Private results As New saveresults

Structure saveresults 'Structure for saving results
    Dim numright As Integer
    Dim numwrong As Integer
    Dim totalnum As Integer
End Structure
'Update the data
Private Sub UpdateResults(Correct As Boolean)
    'It is not necessary to include = True when testing a Boolean
    If Correct Then
        'this is a shortcut method of writin results.numright = results.numright + 1
        results.numright += 1
        'A Boolean can only be True or False so if it is not True
        'it must be False so, we can just use an Else
        'No need to check the condition again
    Else
        results.numwrong += 1
    End If
    results.totalnum += 1
End Sub
'Write text file
Private Sub SaveResultsFile(results As saveresults, correct As Boolean)
    Dim sb As New StringBuilder
    sb.AppendLine(results.numright.ToString)
    sb.AppendLine(results.numwrong.ToString)
    sb.AppendLine(results.totalnum.ToString)
    File.WriteAllText("1.txt", sb.ToString)
End Sub
'Read the text file
Private Function ReadResultsFile() As saveresults
    Dim ResultsFiLe() = File.ReadAllLines("1.txt")
    Dim results As New saveresults With
    {
       .numright = CInt(ResultsFiLe(0)),
       .numwrong = CInt(ResultsFiLe(1)),
       .totalnum = CInt(ResultsFiLe(2))
    }
    Return results
End Function
'Display
Private Sub DisplayResults()
    Dim ResultsToDisplay As saveresults = ReadResultsFile()
    'The $ indicates an interpolated string, the same thing can be accomplished with String.Format
    Label1.Text = $"The correct number is {ResultsToDisplay.numright}. The wrong number is {ResultsToDisplay.numwrong}. The total is {ResultsToDisplay.totalnum}."
End Sub
0 голосов
/ 05 февраля 2019

Используйте это вместо

 FileOpen(1, "1.txt", OpenMode.Binary)

Используя вышеизложенное, вы откроете файл в папке отладки вашего проекта.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...