将收藏夹保存在XML文件中

时间:2018-02-04 12:10:14

标签: c# xml

由于我不想使用数据库保存此信息,因此我尝试将用户收藏夹保存到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文件而不是完全覆盖它?

提前感谢您的回答。

1 个答案:

答案 0 :(得分:0)

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

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

results