【问题标题】:Saving favorites in an XML file [closed]将收藏夹保存在 XML 文件中 [关闭]
【发布时间】:2018-02-04 12:10:13
【问题描述】:

由于我不想使用数据库来保存这些信息,我正在尝试将用户收藏夹保存到 Xml 文件中并稍后加载它们。

目前我正在使用此代码,但这会完全覆盖以前的 Xml 文件,而不是添加到它:

//Creates new filestream with create and write permissions
FileStream fs = new FileStream("Favo.Xml", FileMode.Create, FileAccess.Write);
//Calls SavoFace.cs
SaveFavo sf = new SaveFavo();
//Fills public string Name with tbname.text
sf.Name = tbName.Text;

lvFavo.Items.Add(tbName.Text);
//Adds name to the list
ls.Add(sf);

//Serializes the filestream and the list
xs.Serialize(fs, ls);
//Closes the file
fs.Close();

(此代码来自 youtube 视频,因为我以前从未使用过 Xml 文件,但我似乎无法找到这个特定问题的答案。)

我将如何添加到 Xml 文件而不是完全覆盖它?

提前感谢您的回答。

【问题讨论】:

  • 你明确使用FileMode.Create,你有没有阅读描述?
  • 您的解决方案有多个无法读取的 xml 标识行。附加您必须删除 id 行,然后您将在根级别拥有多个元素,这是一个格式不正确的 xml。所以在阅读的时候你需要将xml阅读器设置为Fragments。

标签: c# xml


【解决方案1】:

这是一个基于您的代码的工作示例

    class Program
{

    static void Main(string[] args)
    {
        List<SaveFavo> ls = new List<SaveFavo>();
        bool bExists = File.Exists("Favo.Xml");
        XmlSerializer xs = new XmlSerializer(typeof(List<SaveFavo>));
        if (!bExists)
        {
            //creates file if file doesn't exist
            using (FileStream fs = File.Create("Favo.Xml"))
            {

                AddFavo(ls, "Test1");
                xs.Serialize(fs, ls);

                //Closes the file
                fs.Close();

            }
        }
        else
        {

            var fs = File.Open("Favo.Xml", FileMode.OpenOrCreate);

            //reads existing file and deserialize into list<SaveFavo>
            ls = xs.Deserialize(fs) as List<SaveFavo>;
            fs.Close();
        }
        //test sample 
        for (int i = 2; i < 10; i++)
            using (FileStream fs = File.OpenWrite("Favo.Xml"))
            //add new content and saves file
            {
                AddFavo(ls, $"Test{i}");
                xs.Serialize(fs, ls);
                fs.Close();
            }

    }

    private static void AddFavo(List<SaveFavo> ls, string favo)
    {
        SaveFavo sf = new SaveFavo();
        //Fills public string Name with tbname.text
        sf.Name = favo;

        //Adds name to the list
        ls.Add(sf);
    }
}

public class SaveFavo
{
    public string Name { get; set; }
    public SaveFavo() { }
}

【讨论】:

    猜你喜欢
    • 2013-05-30
    • 1970-01-01
    • 1970-01-01
    • 2020-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-20
    • 1970-01-01
    相关资源
    最近更新 更多