註冊表/ configurationSettings/XML的說法似乎仍然非常活躍。隨着技術的發展,我已經全部使用了它們,但我最喜歡的是基於Threed's system與Isolated Storage的組合。
以下示例允許將名爲properties的對象存儲到獨立存儲中的文件中。如:
AppSettings.Save(myobject, "Prop1,Prop2", "myFile.jsn");
屬性可以使用恢復:
AppSettings.Load(myobject, "myFile.jsn");
這僅僅是一個樣品,不提示的最佳做法。
internal static class AppSettings
{
internal static void Save(object src, string targ, string fileName)
{
Dictionary<string, object> items = new Dictionary<string, object>();
Type type = src.GetType();
string[] paramList = targ.Split(new char[] { ',' });
foreach (string paramName in paramList)
items.Add(paramName, type.GetProperty(paramName.Trim()).GetValue(src, null));
try
{
// GetUserStoreForApplication doesn't work - can't identify.
// application unless published by ClickOnce or Silverlight
IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForAssembly();
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(fileName, FileMode.Create, storage))
using (StreamWriter writer = new StreamWriter(stream))
{
writer.Write((new JavaScriptSerializer()).Serialize(items));
}
}
catch (Exception) { } // If fails - just don't use preferences
}
internal static void Load(object tar, string fileName)
{
Dictionary<string, object> items = new Dictionary<string, object>();
Type type = tar.GetType();
try
{
// GetUserStoreForApplication doesn't work - can't identify
// application unless published by ClickOnce or Silverlight
IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForAssembly();
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(fileName, FileMode.Open, storage))
using (StreamReader reader = new StreamReader(stream))
{
items = (new JavaScriptSerializer()).Deserialize<Dictionary<string, object>>(reader.ReadToEnd());
}
}
catch (Exception) { return; } // If fails - just don't use preferences.
foreach (KeyValuePair<string, object> obj in items)
{
try
{
tar.GetType().GetProperty(obj.Key).SetValue(tar, obj.Value, null);
}
catch (Exception) { }
}
}
}
這是一個.NET WinForms應用程序嗎?如果是這樣,你在開發什麼版本的.NET? – Portman 2009-01-17 13:20:38
是的,它是一個.NET Framework版本3.5 WinForms應用程序。 – Fueled 2009-01-17 15:15:40
你需要保存**密碼或祕密值**嗎?可能需要任何_encryption_ – Kiquenet 2015-09-21 06:31:41