我在运行时保存应用程序设置时遇到了一些问题...
如果我将设置范围更改为用户,它就可以正常工作,但在应用程序范围内,什么也没有发生...
我使用了:
Properties.Settings.Default.Save();
有什么想法吗?谢谢。
我在运行时保存应用程序设置时遇到了一些问题...
如果我将设置范围更改为用户,它就可以正常工作,但在应用程序范围内,什么也没有发生...
我使用了:
Properties.Settings.Default.Save();
这是因为将范围设置为应用程序会使其变为只读。
请参见《C#中使用设置》
应用程序范围的设置是只读的,只能在设计时或在应用程序会话之间通过修改 .exe.config 文件进行更改。然而,用户范围的设置可以在运行时编写,就像更改任何属性值一样。新值持续整个应用程序会话。您可以通过调用Settings.Save方法来在应用程序会话之间保留对用户设置所做的更改。
您可以像所有高级程序一样在注册表中保存和读取设置,以下是如何操作:
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
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
Properties.Settings
很麻烦,所以我提供了另外两个选择来保存您的应用程序设置:注册表或二进制文件。 - Amen Ayach看看这篇文章吧。你只需要像这样引用应用程序范围的设置:
Properties.Settings.Default["SomeProperty"] = "Some Value";
Properties.Settings.Default.Save(); // Saves settings in application configuration file
对我来说很有效。