如何写入/读取“设置";文本文件 [英] how to write to/read from a "settings" text file

查看:16
本文介绍了如何写入/读取“设置";文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个 Timer 程序,该程序允许用户为计算机上的每个用户帐户设置一个计时器.我在将设置写入文本文件并从中读取时遇到了一些问题.我想知道是否可以以这种方式编写 --> 用户名;允许时间;持续登录;剩余时间;<-- 为每个用户一行,我将如何去做?我还想知道是否可以通过这种方式更改文本文件,如果已经有用户条目,只更改 allowedTime 或剩余时间,有点只是更新文件?

I'm working on a Timer program, that allows the user to set up a timer for each individual user account on the computer. I'm having some trouble writing the settings to a text file and reading from it. I want to know if it's possible to write it in this fashion --> username; allowedTime; lastedLoggedIn; remainingTime; <-- in one line for each user, and how would I go about doing that? I also wanted to know if it's possible to alter the text file in this way, in the case that there's already an entry for a user, only change the allowedTime, or the remainingTime, kinda just updating the file?

此外,我也无法读取文本文件.首先,我不知道如何确定所选用户是否在文件中.在那里形成,如果用户在文件中列出,如何访问该行的其余部分,例如仅获取该用户的 allowedTime 或剩余时间?

Also I'm also having trouble being able to read from the text file. First of all I can't figure out how to determine if a selected user is in the file or not. Form there, if the user is listed in the file, how can access the rest of the line, like only get the allowedTime of that user, or the remaining time?

我尝试了几种方法,但我无法让它按照我的方式成像,如果有道理的话.这是到目前为止的代码:

I tried a couple of ways, but i just can't get it to do how I'm imaging it, if that makes sense. here's the code so far:

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

我只是想确定我的序列化是否正确,反序列化是否相同.这是我目前得到的:

edit: I just wanted to make sure if I'm doing the serialization right and the same for the deserialization. this is what i got so far:

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

我对 try/catch 不太熟悉,但是这会起作用吗?

edit 2: I'm not too familiar with try/catch but would this work instead?

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

推荐答案

您的代码中有一些拼写错误等,但您的第一次尝试非常接近:

You have a few typos and such in your code, but it is pretty close for your first try:

Friend userList As New List(Of Users)

Public Sub saveUserSetting()
    ' NOTE: Using the BINARY formatter will write a binary file, not XML
    Using fs As New System.IO.FileStream("Settings.bin", IO.FileMode.OpenOrCreate)
        Dim bf As New BinaryFormatter
        bf.Serialize(fs, userList)
    End Using
End Sub

Public Sub readUserSettings()
    ' this doesnt seem needed:
    Dim currentUser As String = GetUserName()

    ' do not want the following line - it will create a NEW
    ' useRlist which exists only in this procedure
    ' you probably want to deserialize to the useRlist
    ' declared at the module/class level
    ' Dim useList As New List(Of Users)

    ' a) Check if the filename exists and just exit with an empty
    '    useRlist if not (like for the first time run).

    ' b) filemode wass wrong - never create here, just read
    Using fs As New System.IO.FileStream("Settings.bin", 
                 FileMode.Open, FileAccess.Read)
        Dim bf As New BinaryFormatter
        '  user list is declared above as useRList, no useList
        useList = bf.Deserialize(fs)
    End Using
    ' Console.WriteLine is much better for this
    MessageBox.Show(useList(0).ToString)
End Sub

<Serializable>
Class Users
    ' I would make this a property also
    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

待办事项:

a) 决定您要保存 XML 还是二进制文件.使用 XML,用户可以读取/编辑文件.

a) decide whether you want XML or binary saves. With XML, users can read/edit the file.

b) 使用从 Environment.GetFolder() 创建的文件路径;使用字符串文字,它在部署时可能会出现在Program Files"中,并且您无法在那里写入.

b) Use a file path created from Environment.GetFolder(); with a string literal it may end up in 'Program Files' when deployed, and you cannot write there.

c) 在读取/加载 useRlist 时,使用类似

c) when reading/loading the useRlist, use something like

FileStream(myUserFile, FileMode.Open, FileAccess.Read)

第一次运行时它不会存在,所以检查它是否存在并将列表留空.之后,您只需要打开它即可阅读.为了节省使用类似的东西:

It wont exist the first time run, so check if it does and just leave the list empty. After that, you just need to open it for reading. For saving use something like:

 FileStream(myUserFile, FileMode.OpenOrCreate, FileAccess.Write)

您想创建它并写入它.您可以将加载/保存代码放在 Try/Catch 中,这样如果存在文件访问问题,您就可以捕获并报告它们,这样您就知道该列表没有被保存或读取.

You want to create it and write to it. You might put the Load/Save code inside a Try/Catch so if there are file access issues you can trap and report them, and so you know the list did not get saved or read.

使用序列化程序,列表的全部内容 - 无论多长 - 都将与那 3-4 行代码一起保存,并且整个列表在 2-3 行中读回以加载/读取文件.

Using a serializer, the entire contents of the list - no matter how long - will get saved with those 3-4 lines of code, and the entire list read back in the 2-3 lines to load/read the file.

这篇关于如何写入/读取“设置";文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆