как писать / читать из текстового файла «настройки»

Я работаю над программой Timer, которая позволяет пользователю настроить таймер для каждой отдельной учетной записи пользователя на компьютере. У меня возникли проблемы с записью настроек в текстовый файл и чтением из него. Я хочу знать, возможно ли написать это таким способом -> username; allowedTime; lastedLoggedIn; оставшееся время; <- в одной строке для каждого пользователя, и как мне это сделать? Я также хотел знать, возможно ли изменить текстовый файл таким образом, в случае, если для пользователя уже есть запись, изменить только allowTime или оставшееся время, просто обновить файл?

Кроме того, у меня также возникают проблемы при чтении из текстового файла. Прежде всего я не могу понять, как определить, находится ли выбранный пользователь в файле или нет. Форма там, если пользователь указан в файле, как получить доступ к остальной части строки, например, получить только allowTime этого пользователя или оставшееся время?

Я попробовал несколько способов, но я просто не могу заставить его делать то, что я себе представляю, если это имеет смысл. вот код на данный момент:

Public Sub saveUserSetting(ByVal time As Integer)
    Dim hash As HashSet(Of String) = New HashSet(Of String)(File.ReadAllLines("Settings.txt"))
    Using w As StreamWriter = File.AppendText("Settings.txt")
        If Not hash.Contains(selectedUserName.ToString()) Then
            w.Write(selectedUserName + "; ")
            w.Write(CStr(time) + "; ")
            w.WriteLine(DateTime.Now.ToLongDateString() + "; ")
        Else
            w.Write(CStr(time) + "; ")
            w.WriteLine(DateTime.Now.ToLongDateString() + "; ")
        End If
    End Using
End Sub

Public Sub readUserSettings()
    Dim currentUser As String = GetUserName()
    Dim r As List(Of String) = New List(Of String)(System.IO.File.ReadLines("Settings.txt"))
    'For Each i = 0 to r.lenght - 1

    'Next
    'check to see if the current user is in the file
    MessageBox.Show(r(0).ToString())
    If r.Contains(selectedUserName) Then
        MessageBox.Show(selectedUserName + " is in the file.")
        'Dim allowedTime As Integer
    Else
        MessageBox.Show("the user is not in the file.")

    End If
    'if the name is in the file then
    'get the allowed time and the date
    'if the date is older than the current date return the allowed time
    'if the date = the current date then check thhe remaning time and return that
    'if the date is ahead of the current date return the reamining and display a messgae that the current date needs to be updated.
End Sub

редактировать: я просто хотел убедиться, что я делаю сериализацию правильно и то же самое для десериализации. это то, что я получил так далеко:

Friend userList As New List(Of Users)

Public Sub saveUserSetting()
    Using fs As New System.IO.FileStream("Settings.xml", IO.FileMode.OpenOrCreate)
        Dim bf As New BinaryFormatter
        bf.Serialize(fs, userList)
    End Using
End Sub

Public Sub readUserSettings()
    Dim currentUser As String = GetUserName()
    Dim useList As New List(Of Users)
    Using fs As New System.IO.FileStream("Settings.xml", IO.FileMode.OpenOrCreate)
        Dim bf As New BinaryFormatter
        useList = bf.Deserialize(fs)
    End Using
    MessageBox.Show(useList(0).ToString)
End Sub

<Serializable>
Class Users
    Public userName As String
    Public Property allowedTime As Integer
    Public Property lastLoggedInDate As String
    Public Property remainingTime As Integer
    Public Overrides Function ToString() As String
        Return String.Format("{0} ({1}, {2}, {3})", userName, allowedTime, lastLoggedInDate, remainingTime)
    End Function
End Class

редактировать 2: я не слишком знаком с try / catch, но будет ли это работать вместо этого?

Public Sub readUserSettings()
    If System.IO.File.Exists("Settings") Then
        Using fs As New System.IO.FileStream("Settings", FileMode.Open, FileAccess.Read)
            Dim bf As New BinaryFormatter
            userList = bf.Deserialize(fs)
        End Using
    Else
        MessageBox.Show("The setting file doesn't exists.")
    End If
End Sub

Ответы на вопрос(2)

Ваш ответ на вопрос