como gravar / ler em um arquivo de texto "settings"
Estou trabalhando em um programa de timer, que permite ao usuário configurar um timer para cada conta de usuário individual no computador. Estou tendo problemas para gravar as configurações em um arquivo de texto e ler a partir dele. Quero saber se é possível escrevê-lo dessa maneira -> nome de usuário; allowedTime; lastedLoggedIn; tempo restante; <- em uma linha para cada usuário, e como eu faria isso? Eu também queria saber se é possível alterar o arquivo de texto dessa maneira, caso já exista uma entrada para um usuário, apenas altere o allowedTime ou o restanteTime, meio que atualizando o arquivo?
Também estou tendo problemas para ler o arquivo de texto. Primeiro de tudo, não consigo descobrir como determinar se um usuário selecionado está no arquivo ou não. Ali, se o usuário estiver listado no arquivo, como acessar o restante da linha, como apenas obter o tempo permitido desse usuário ou o tempo restante?
Eu tentei de duas maneiras, mas eu simplesmente não consigo entender como estou imaginando, se isso faz sentido. aqui está o código até agora:
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.ToLongDateStr,ing() + "; ")
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
edit: Eu só queria ter certeza de que estou fazendo a serialização correta e a mesma para a desserialização. isto é o que eu tenho até agora:
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
editar 2: Eu não estou muito familiarizado com try / catch, mas isso funcionaria?
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