如何写入/读取“设置”文本文件
Posted
技术标签:
【中文标题】如何写入/读取“设置”文本文件【英文标题】:how to write to/read from a "settings" text file 【发布时间】:2014-08-13 22:38:40 【问题描述】:我正在开发一个计时器程序,它允许用户为计算机上的每个用户帐户设置一个计时器。我在将设置写入文本文件并从中读取时遇到了一些问题。我想知道是否可以以这种方式编写它-->用户名;允许时间;持续登录;剩余时间;
另外,我也无法从文本文件中读取。首先,我不知道如何确定所选用户是否在文件中。表单那里,如果用户在文件中列出,如何访问该行的其余部分,例如只获取该用户的 allowedTime 或剩余时间?
我尝试了几种方法,但如果这有意义的话,我就是无法让它像我想象的那样去做。 这是到目前为止的代码:
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
【问题讨论】:
VB 内置了一个完整的Settings
东西。如果您有多个用户,但每个条目都有几条数据,那么序列化 List(of myClass)
可能更容易
我以前使用过Settings
,但它变得有点“笨拙”,有很多用户,每个用户都有几个条目,所以我认为读写文本文件会更干净。我将如何使用List(of myClass)
?你能举个小例子吗?
here is an example 类将相关数据保存在一起比数组更好,您可以通过序列化程序非常轻松地保存/重新加载。
我尝试了序列化方法,我想知道如果我做得正确,是否可以获得一些反馈,特别是对于反序列化方法。提前致谢。
使用 app.config,.NET 内置了对它们的读写支持。
【参考方案1】:
您的代码中有一些拼写错误等,但您的第一次尝试非常接近:
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,用户可以读取/编辑文件。
b) 使用从 Environment.GetFolder() 创建的文件路径;使用字符串文字时,它可能会在部署时出现在“程序文件”中,并且您不能在那里写入。
c) 读取/加载 userRlist 时,使用类似
的内容FileStream(myUserFile, FileMode.Open, FileAccess.Read)
它在第一次运行时不会存在,因此请检查它是否存在并将列表留空。之后,您只需打开它即可阅读。为了节省使用类似的东西:
FileStream(myUserFile, FileMode.OpenOrCreate, FileAccess.Write)
您想创建它并写入它。您可以将加载/保存代码放在 Try/Catch 中,这样如果存在文件访问问题,您可以捕获并报告它们,这样您就知道列表没有被保存或读取。
使用序列化程序,列表的全部内容(无论多长时间)都将与这 3-4 行代码一起保存,并且整个列表在 2-3 行中读回以加载/读取文件。
【讨论】:
感谢您迄今为止的所有帮助。我真的很感激。【参考方案2】:我没有你所有问题的答案,但是我也一直在开发一个计时器应用程序,并且最近才开始使用文本文件来读取和写入信息。我使用的方法已经证明它很容易使用并且不会很混乱。这是我的代码的摘录:
Dim startup As String = "C:\Users\DigiParent\Desktop\Project data\Digitimeinfo.txt"
Dim reader As New System.IO.StreamReader(startup, Encoding.Default)
Dim data As String = reader.ReadToEnd
Dim aryTextFile(6) As String
aryTextFile = data.Split(",")
这将读取文本文件中的所有内容,并在排序中将 之间的所有内容分开,并将它们单独存储在数组中。要将代码放回一行,请使用
Dim LineOfText As String
LineOfText = String.Join(",", aryTextFile)
所以你可以写这样的东西来将你的信息写入文本文件:
Dim startup As String = "C:\Users\DigiParent\Desktop\Project data\Digitimeinfo.txt"
Dim objWriter As New System.IO.StreamWriter(startup, False)
Dim aryTextFile(2) As String
aryTextFile(0) = pasword
aryTextFile(1) = user
aryTextFile(2) = remainingtime
LineOfText = String.Join(",", aryTextFile)
objWriter.WriteLine(LineOfText)
objWriter.Close()
要阅读它,您可以使用 Steam 阅读器。
【讨论】:
我也试试看。以上是关于如何写入/读取“设置”文本文件的主要内容,如果未能解决你的问题,请参考以下文章