简体   繁体   中英

Trouble saving C# WPF

I am making an application for a 'Ski Resort' where you can add members and search members etc. So far I am having difficulty saving and loading these when the application closes. When I add a member, it saves, and then when I try to add another, the first member will not be saved anymore but the first one will have done. Here is the code used to Save the members:

     public void Save(System.IO.TextWriter textOut)
    {
        textOut.WriteLine(number);
        textOut.WriteLine(name);
        textOut.WriteLine(address);
        textOut.WriteLine(score);
        textOut.Close();
    }

    public bool Save(string filename)
    {
        System.IO.TextWriter textOut = null;
        try
        {
            textOut = new System.IO.StreamWriter(filename);
            Save(textOut);
        }
        catch
        {
            return false;
        }
        finally
        {
            if (textOut != null)
            {
                textOut.Close();
            }
        }
        return true;
    }

The StreamWriter constructor you are using will overwrite the file each time. Use the constructor that also takes a boolean so you can make it append to the file. And you don't need the TextWriter .

try
{
   using(var textOut = new System.IO.StreamWriter(filename, true))
   {
       textOut.WriteLine("whatever..");
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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