繁体   English   中英

C#在应用程序内动态进行设置,然后永久保存

[英]C# Dynamically make settings within application then save persistently

我正在寻找许多不同的方式来做到这一点,但我不确定应该走的方向...

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

想法是用户将能够在应用程序列表中进行选择。 这些应用程序将被保存,直到用户将其删除为止。 我需要保存应用程序名称和相应的路径。

问题在于,我似乎无法将键,值对保存到Visual Studio中的新设置,并使它们持久化。 我需要写一个文件来保存文件,我该怎么做...我应该将它们写到system.configuration,JSON还是XML? 有人有很好的演练吗?

好吧,有很多方法可以做到这一点。 对于一种简单的方法,可以使用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();

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

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

使用以下屏幕快照中的说明将设置添加到设置:

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

在此处输入图片说明

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

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();
        }
    }
}

设置将存储在用户的配置文件中

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM