那麼,有很多方法可以做到這一點。對於一種簡單的方法,您可以使用XML序列化。首先創建一個代表所有要保存設置一個類,Serializable屬性添加到它,比如:
[Serializable]
public class AppSettings
{
public List<UserApp> Applications { get; set; }
}
[Serializable]
public class UserApp
{
public string Path { get; set; }
public string Name { get; set; }
}
接着,下面的方法添加到它:
public static void Save(AppSettings settings)
{
string xmlText = string.Empty;
var xs = new XmlSerializer(settings.GetType());
using (var xml = new StringWriter())
{
xs.Serialize(xml, settings);
xml.Flush();
xmlText = xml.ToString();
}
string roamingPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
File.WriteAllText(roamingPath + @"\settings.xml", xmlText);
}
public static AppSettings Load()
{
string roamingPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
if (!File.Exists(roamingPath + @"\settings.xml"))
return new AppSettings();
string xmlText = File.ReadAllText(roamingPath + @"\settings.xml");
var xs = new XmlSerializer(typeof(AppSettings));
return (AppSettings)xs.Deserialize(new StringReader(xmlText));
}
然後,保存,這樣做:
AppSettings settings = new AppSettings();
settings.Applications = new List<UserApp>();
settings.Applications.Add(new UserApp { Path = @"C:\bla\foo.exe", Name = "foo" });
AppSettings.Save(settings);
並加載:
AppSettings settings = AppSettings.Load();
您也可以編輯加載的設置並再次保存,覆蓋舊的設置。
如需更多更復雜的方法,請保存到數據庫中。
爲了保持簡單,我只需將一些JSON或XML文本文件寫入運行該應用程序的計算機的驅動器即可。 – MAlvarez