我在运行时保存应用程序设置时遇到一些问题......
如果我将设置范围更改为用户,它可以正常工作,但在应用范围内,没有任何事情发生......
我用过:
Properties.Settings.Default.Save();
任何想法?
感谢
答案 0 :(得分:10)
这是因为将范围设置为Application会使其成为只读。
应用程序范围设置是只读的,只能在设计时更改或在应用程序会话之间更改.exe.config文件。但是,用户范围设置可以在运行时写入,就像更改任何属性值一样。新值在应用程序会话期间保持不变。您可以通过调用Settings.Save方法在应用程序会话之间保留对用户设置的更改。
答案 1 :(得分:1)
您可以像注册表中的所有高级程序一样保存和读取设置,这就是如何操作:
Public Function GetRegistryValue(ByVal KeyName As String, Optional ByVal DefaultValue As Object = Nothing) As Object
Dim res As Object = Nothing
Try
Dim k = My.Computer.Registry.CurrentUser.OpenSubKey("Software\YourAppName", True)
If k IsNot Nothing Then
res = k.GetValue(KeyName, DefaultValue)
Else
k = My.Computer.Registry.CurrentUser.CreateSubKey("Software\YourAppName")
End If
If k IsNot Nothing Then k.Close()
Catch ' ex As Exception
'PromptMsg(ex)
End Try
Return res
End Function
Public Sub SetRegistryValue(ByVal KeyName As String, ByVal _Value As Object)
Try
Dim k = My.Computer.Registry.CurrentUser.OpenSubKey("Software\YourAppName", True)
If k IsNot Nothing Then
k.SetValue(KeyName, _Value)
Else
k = My.Computer.Registry.CurrentUser.CreateSubKey("Software\YourAppName")
k.SetValue(KeyName, _Value)
End If
If k IsNot Nothing Then k.Close()
Catch ' ex As Exception
'PromptMsg(ex)
End Try
End Sub
甚至可以创建一个包含所有设置属性的可序列化类( [Serializable()] attrib),然后使用BinaryFormatter类将其保存在app目录中。< / p>
Public Sub saveBinary(ByVal c As Object, ByVal filepath As String)
Try
Using sr As Stream = File.Open(filepath, FileMode.Create)
Dim bf As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter()
bf.Serialize(sr, c)
sr.Close()
End Using
Catch ex As Exception
Throw ex
End Try
End Sub
Public Function loadBinary(ByVal path As String) As Object
Try
If File.Exists(path) Then
Using sr As Stream = File.Open(path, FileMode.Open)
Dim bf As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter()
Dim c = bf.Deserialize(sr)
sr.Close()
Return c
End Using
Else
Throw New Exception("File not found")
End If
Catch ex As Exception
Throw ex
End Try
Return Nothing
End Function
答案 2 :(得分:0)
检查this post。您只需参考应用程序作用域设置,如下所示:
Properties.Settings.Default["SomeProperty"] = "Some Value";
Properties.Settings.Default.Save(); // Saves settings in application configuration file
为我工作。