C#在应用程序中保存文件位置

时间:2012-10-04 20:52:07

标签: c# .net winforms settings

我希望用户能够选择程序文件在其PC中的位置,并在每次启动应用程序时保存该位置,直到他们更改它为止。我从来没有用C#做过这样的事情,我仍然认为自己是C#的新手。我已经考虑过创建一个Settings.txt文件或XML文件并读取用户保存的行,但我仍然不确定如何存储它。任何帮助或建议将不胜感激。

4 个答案:

答案 0 :(得分:0)

制作您自己的文件类型以保存特定数据听起来不错,首先要开始。

当你开发你的程序时,你可能会发现有点限制但要学习我会从脑海中想到的任何解决方案开始,然后你可能会认识到哪些部分需要重新设计以提高效率或实用性。

答案 1 :(得分:0)

最简单的方法可能是为此目的使用.NET User Settings

还有很多其他选项,包括Isolated Storage,甚至使用the Application class公开的目录或注册表项之一(UserAppDataPath,LocalUserAppDataPath,UserAppDataRegistry,...)

答案 2 :(得分:0)

void Main()
{
    // Settings in a Text File
    string path1 = @"C:\\Dev\\settings.txt";
    string setting1;
    string setting2;
    setting1 = "foo";
    setting2 = "bar";
    SaveSettingsToTextFile(path1, setting1, setting2);
    setting1 = "";
    setting2 = "";
    LoadSettingsFromTextFile(path1, out setting1, out setting2);
    Console.WriteLine(setting1);
    Console.WriteLine(setting2);

    // Settings in an Xml File
    string path2 = @"C:\\Dev\\settings.xml";
    MySettings mySettings = MySettings.Create(path2);
    mySettings.setting1 = "bat";
    mySettings.setting2 = "baz";
    mySettings.Save();  
    mySettings = null;
    mySettings = MySettings.Create(path2);
    Console.WriteLine(mySettings.setting1);
    Console.WriteLine(mySettings.setting2);
}

void SaveSettingsToTextFile(string path, string setting1, string setting2)
{
    var sb = new StringBuilder();
    sb.AppendLine(setting1);
    sb.AppendLine(setting2);
    File.WriteAllText(path, sb.ToString());
}

void LoadSettingsFromTextFile(string path, out string setting1, out string setting2)
{
    var lines = File.ReadLines(path).ToArray();
    setting1 = lines[0];
    setting2 = lines[1];
}

public class MySettings
{
    public string setting1 { get; set; }
    public string setting2 { get; set; }

    static XmlSerializer serializer = new XmlSerializer(typeof(MySettings));

    public static MySettings Create(string savePath)
    {
        MySettings instance;
        if(File.Exists(savePath))
        {
            var xDoc = XDocument.Load(savePath);
            var reader = xDoc.CreateReader();
            instance = (MySettings)serializer.Deserialize(reader);
            reader.Close();
        }
        else
        {
            instance = new MySettings();
        }
        instance.SavePath = savePath;
        return instance;
    }

    public void Save()
    {
        var xDoc = new XDocument();
        var writer = xDoc.CreateWriter();
        serializer.Serialize(writer, this);
        writer.Close();
        File.WriteAllText(this.SavePath, xDoc.ToString());
    }

    [XmlIgnore]
    public string SavePath { get; private set; }
}

输出:

foo
bar
bat
baz

答案 3 :(得分:0)

最简单的方法是将设置文本文件或xml文件添加到项目中,然后使用您的C#代码更新它。这非常简单,所以我不会在这里详细介绍如何做到这一点。只需Google搜索c#中的文本文件。