C# 在应用程序中动态进行设置然后持久保存

C# Dynamically make settings within application then save persistently

我找到了很多不同的方法来做到这一点,但我不确定我应该走的方向...

我有一个应用程序可以在多台个人计算机上 运行。我正在寻找一种方法来持久保留应用程序设置列表。

想法是用户将能够在应用程序列表中进行选择。然后将保存这些应用程序,直到用户删除它们。我需要保存应用名称和对应的路径

问题是我似乎无法将键值对保存到 visual studio 中的新设置并让它们持续存在。我需要写一个文件来保存文件,我该怎么做...我应该把它们写到 system.configuration、JSON 还是 XML???有没有人有好的攻略?

好吧,有很多方法可以做到这一点。对于简单的方法,您可以使用 XML 序列化。首先创建一个class代表你要保存的所有设置,并为其添加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();

您也可以编辑加载的设置并再次保存,覆盖旧的。

对于更复杂的方法,请保存到数据库中。

使用以下屏幕截图中显示的说明向设置添加设置:

注意:双击第一个箭头所示的属性

然后您可以像这样在运行时更新该值:

namespace ConsoleApplication1
{
    public class Program
    {
        public static void Main()
        {
            var defSettings = ConsoleApplication1.Properties.Settings.Default;
            var props = defSettings.Test = "Whatever";

            // Save it so it persists between application start-ups
            defSettings.Save();

            Console.Read();
        }
    }
}

设置将存储在 user's profile