我的项目中有一个 Settings.cs 文件,我通过以下方式从程序访问其中的数据
Properties.Settings.Default.MyProperty
生成的设置文件存储在以下位置
C:\Users\Foo\AppData\Local\MyApp\MyApp.exe_Url_jknwq2raeohczydfp1loj02nf05zldfk\1.0.0.0\user.config
问题是,这不仅是特定于用户的,而且还会导致程序为每个签名(调试/发布等)提供许多 user.config 文件,这迫使开发人员用户每次都再次填充整个设置他启动了该程序的一个“版本”,该程序还没有特定的 user.config。 (如果我还不够清楚,我很乐意提供更多细节)
我希望我的应用程序为所有用户提供一个设置文件,无论“版本”如何(调试/发布或其他)。这样,开发用户必须一次性设置这些设置,并且这些设置将在每次启动应用程序时生效,而无需为其他签名/用户重新输入它们。
您可以像所有高级程序一样保存和读取设置Registry,这就是如何做到这一点:
public object GetRegistryValue(string KeyName, object DefaultValue)
{
object res = null;
try
{
Microsoft.VisualBasic.Devices.Computer c = new Microsoft.VisualBasic.Devices.Computer();
Microsoft.Win32.RegistryKey k = c.Registry.CurrentUser.OpenSubKey("Software\\YourAppName", true);
if (k != null)
{
res = k.GetValue(KeyName, DefaultValue);
}
else
{
k = c.Registry.CurrentUser.CreateSubKey("Software\\YourAppName");
}
if (k != null)
k.Close();
// ex As Exception
}
catch
{
//PromptMsg(ex)
}
return res;
}
public void SetRegistryValue(string KeyName, object _Value)
{
try
{
Microsoft.VisualBasic.Devices.Computer c = new Microsoft.VisualBasic.Devices.Computer();
Microsoft.Win32.RegistryKey k = c.Registry.CurrentUser.OpenSubKey("Software\\YourAppName", true);
if (k != null)
{
k.SetValue(KeyName, _Value);
}
else
{
k = c.Registry.CurrentUser.CreateSubKey("Software\\YourAppName");
k.SetValue(KeyName, _Value);
}
if (k != null)
k.Close();
// ex As Exception
}
catch
{
//PromptMsg(ex)
}
}
Another您可以选择创建一个可序列化的类([可序列化()]attrib) 包含所有设置作为属性,然后使用 BinaryFormatter 类将其保存在您的应用程序目录中。
public void saveBinary(object c, string filepath)
{
try
{
using (System.IO.Stream sr = System.IO.File.Open(filepath, System.IO.FileMode.Create))
{
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
bf.Serialize(sr, c);
sr.Close();
}
}
catch (Exception ex)
{
throw ex;
}
}
public object loadBinary(string path)
{
try
{
if (System.IO.File.Exists(path))
{
using (System.IO.Stream sr = System.IO.File.Open(path, System.IO.FileMode.Open))
{
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
object c = bf.Deserialize(sr);
sr.Close();
return c;
}
}
else
{
throw new Exception("File not found");
}
}
catch (Exception ex)
{
throw ex;
}
return null;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)