我的VS2013 VB应用程序目前将设置保存到注册表中,它已经发展到了困扰我的程度。所以我想将设置(字符串)保存到文件中。奖金是他们可以在网络上并由多个用户使用。可能有数百甚至数千行。使用的首选格式是什么?旧的INI,CSV,XML?在我看来,设置文件似乎不是一个很好的选择。
答案 0 :(得分:0)
我强烈建议创建一个类的对象,并对.NET应用程序的XML使用序列化。它易于实现,完全支持,您可以将设置从一台计算机导入和导出到另一台计算机。您甚至可以将应用程序设置为准备网络设置。此外,它将使未来的编程/升级更容易。
我在这里列出一个工作示例(经过测试)。该代码自2012年开始使用,完美适用于企业级应用程序。
注意:我只为演示添加了一个“设置项目”,因此您可以添加自己的。
首先:设置或选项类:
Imports System.Xml.Serialization
Imports System.IO
<Serializable()> _
Public Class Options
Public KEYS_USE_LISTS As Boolean
Public Sub New()
KEYS_USE_LISTS = True
End Sub
#Region "Methods"
Public Sub Save(ByVal Path As String)
Try
Dim _XMLSerilizer As New XmlSerializer(GetType(Options))
Dim _StreamWriter As New StreamWriter(Path)
_XMLSerilizer.Serialize(_StreamWriter, Me)
_StreamWriter.Close()
Catch ex As Exception
MsgBox("Error saving database setting." & vbCrLf & "Internal Error: " & ex.Message)
End Try
End Sub
Public Function DoLoad(ByVal Path As String) As Options
Dim _Opt As New Options
Try
If IO.File.Exists(Path) Then
Dim _XMLSerilizer As New XmlSerializer(GetType(Options))
Dim _FileStream As New FileStream(Path, FileMode.Open)
_Opt = DirectCast(_XMLSerilizer.Deserialize(_FileStream), Options)
_FileStream.Close()
End If
Catch ex As Exception
MsgBox("Error loading database setting." & vbCrLf & "Internal Error: " & ex.Message)
End Try
Return _Opt
End Function
#End Region
End Class
第二:通过界面(例如WinForms)
使用它Public Class frmOptions
Public _options As New Options
Private Sub frmOptions_Load(sender As Object, e As EventArgs) Handles MyBase.Load
If IO.File.Exists(Application.StartupPath & "/_Options.opt") Then
_options = _options.DoLoad(Application.StartupPath & "/_Options.opt")
End If
chkUseList.Checked = _options.KEYS_USE_LISTS
End Sub
Private Sub btnOk_Click(sender As Object, e As EventArgs) Handles btnOk.Click
If IO.File.Exists(Application.StartupPath & "/_Options.opt") Then
_options = _options.DoLoad(Application.StartupPath & "/_Options.opt")
End If
_options.KEYS_USE_LISTS = chkUseList.Checked
_options.Save(Application.StartupPath & "/_Options.opt")
Me.DialogResult = Windows.Forms.DialogResult.OK
Me.Close()
End Sub
End Class