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

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

问题描述

我正在开发一个定时器程序,它允许用户为计算机上的每个用户帐户设置一个定时器。我在将设置写入文本文件并从中读取时遇到了一些麻烦。我想知道是否有可能以这种方式写 - >用户名; allowedTime; lastedLoggedIn;剩余时间; < - 在每个用户的一行中,我将如何去做呢?我也想知道是否有可能以这种方式改变文本文件,如果已经有一个用户的条目,只改变allowedTime或剩余时间,只是更新文件?



另外,我也无法从文本文件中读取。首先我不知道如何确定一个选定的用户是否在文件中。在那里,如果用户列在文件中,怎么可以访问剩下的行,比如只获取那个用户的allowedTime,还是剩下的时间?



我尝试了几种方法,但是如果这样做是有道理的,我无法做到如何对其进行成像。
这里的代码到目前为止:

pre $ Public Sub saveUserSetting(ByVal time As Integer)
Dim hash As HashSet(Of String)= New HashSet(Of String)(File.ReadAllLines(Settings.txt))
使用w作为StreamWriter = File.AppendText(Settings.txt)
如果不是散列.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使用
End Sub
$ b 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
'检查当前用户是否在文件
MessageBox.Show(r(0).ToString())
如果r.Contains(selectedUserName)则
MessageBox.Show(selectedUserName +在文件中)
'Dim allowedTime As Integer
else
MessageBox.Show(用户不在文件中)

结束如果
'如果名字是在文件中,然后
'获得允许的时间和日期
'如果日期比当前日期早返回允许的时间
'如果日期=当前日期然后检查重新如果日期早于当前日期,则返回
'返回剩余时间,并显示当前日期需要更新的信息。
结束小组

编辑:我只是想确定我是否在序列化正确和反序列化是一样的。
这是我到目前为止:

 朋友userList作为新的用户列表

公用Sub saveUserSetting()
使用FS作为新System.IO.FileStream( 将Settings.xml,IO.FileMode.OpenOrCreate)
尺寸BF作为新的BinaryFormatter
bf.Serialize (fs,userList)
结束使用
End Sub
$ b Public Sub readUserSettings()
Dim currentUser As String = GetUserName()
Dim useList As New List of Users
使用fs作为新的System.IO.FileStream(Settings.xml,IO.FileMode.OpenOrCreate)
Dim bf As New BinaryFormatter
useList = bf.Deserialize fs)
结束使用
MessageBox.Show(useList(0).ToString)
End Sub

< Serializable>
类用户
公共用户名作为字符串
公共属性allowedTime作为整数
公共属性lastLoggedInDate作为字符串
公共属性remainingTime作为整数
公用重写函数ToString )As String
返回String.Format({0}({1},{2},{3}),userName,allowedTime,lastLoggedInDate,remainingTime)
End Function
End类

编辑2:
我不太熟悉try / catch,工作而不是?

  Public Sub readUserSettings()
如果System.IO.File.Exists(Settings)Then
使用fs作为新的System.IO.FileStream(Settings,FileMode.Open,FileAccess.Read)
Dim bf As New BinaryFormatter
userList = bf.Deserialize(fs)
结束使用
else
MessageBox.Show(设置文件不存在)
End If
End Sub


解决方案

在你的代码中你有几个拼写错误,但是你的第一次尝试是非常接近的:

 $ public $ saveUserSetting()
'注意:使用BINARY格式化程序将写入一个二进制文件,不是XML
使用fs作为新的System.IO.FileStream(Settings.bin,IO.FileMode.OpenOrCreate)
Dim bf As New BinaryFormatter
bf.Serialize(fs,userList)
结束使用
结束Sub

Public Sub readUserSettings()
'这似乎不需要:
Dim currentUser As String = GetUserName()

'不需要下面的行 - 它会创建一个新的
'useRlist,它只存在于这个过程中
',你可能想要反序列化到在这个过程中声明的useRlist
'模块/类级别
'Dim useList作为新列表(用户)

'a)检查文件名是否存在a如果没有(如第一次运行)那么只需要退出一个空的
'useRlist。

'b)filemode错了 - 从来没有在这里创建,只读
使用fs作为新的System.IO.FileStream(Settings.bin,
FileMode.Open,FileAccess .Read)
Dim bf As New BinaryFormatter
'user list is above above useRList,no useList
useList = bf.Deserialize(fs)
End使用
' Console.WriteLine对于这个
好​​多了MessageBox.Show(useList(0).ToString)
End Sub

< Serializable>
类用户
我将这个属性也b $ b公共用户名作为字符串
公共属性allowedTime作为整数
公共财产lastLoggedInDate作为字符串
公共属性remainingTime As Integer
Public Overrides Function ToString()As String
返回String.Format({0}({1},{2},{3}),userName,allowedTime,lastLoggedInDate,remainingTime )
结束函数
结束类

待办事项:

$ b a)决定是否需要XML或二进制保存。使用XML,用户可以读取/编辑文件。

使用从Environment.GetFolder()创建的文件路径。使用字符串文字时,它可能在部署时在程序文件中结束,并且不能在那里写入。



当读取/加载useRlist时, / p>

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

它在第一次运行时不会存在,所以检查它是否存在,并将列表留空。之后,你只需要打开它阅读。为保存使用类似:

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

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



使用序列化程序,列表的全部内容 - 无论多长时间 - 都将被保存在这3-4行代码中,整个列表读回2-3行以加载/读取文件。

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?

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

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

ToDo:

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

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) 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)

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.

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天全站免登陆