0

I would like to store all my snakes, in a snakeList.

When the user creates new snakes, I would like the program to keep them, and store them in a List.

But I don't know how to do that.

If I write:

List<Snake> snakeList = new List<Snake>();

Then, whenever I restart the program, I think it creates a new snakeList every time. I would like to keep using the same snake list, even if the program restarts.

Should I use XML for that?

LopDev
  • 823
  • 10
  • 26
Its_707_not_LOL
  • 13
  • 1
  • 2
  • 7
  • 3
    Yup. You'll need to serialize the list of snakes when the program closes, and then deserialize it when the program loads up again. XML is a good way to go. – Danny Goodall Feb 24 '20 at 10:39
  • you need some sort of storage to persist the data. A database, or an xml file on the file system - something. – Jonesopolis Feb 24 '20 at 10:40
  • I don't think you'd do too badly searching for `loading and saving data in C#` and reading a few articles/posts. I think there's too much to try to fit in an answer here. – Damien_The_Unbeliever Feb 24 '20 at 10:41
  • Depending on the application, you COULD store it in session – JamesS Feb 24 '20 at 10:42
  • 1
    Does this answer your question? [C# .NET - method to store some very small scale persistent information?](https://stackoverflow.com/questions/10323755/c-sharp-net-method-to-store-some-very-small-scale-persistent-information) – Drag and Drop Feb 24 '20 at 10:43
  • It's a broad question that may be answer by : 1/. in database: A, sqlLite, no-db,..etc.. 2/. in file with format: csv, json, xml , etc. 3/. in session depending of your application type. Each of those question may also be too broad as there is a ton a possible database structure format. – Drag and Drop Feb 24 '20 at 10:45
  • @DannyGoodall Thank you! Probably that is what I will do! – Its_707_not_LOL Feb 24 '20 at 10:54

1 Answers1

2

As mentioned, you need to write data to external resource (file, database) in order to persist that data, even when app is closed.

So in order to do that, when program closes, you need to write it to disk, for example (I used serialization to JSON, you can use other method):

string json = JsonConvert.SerializeObject(snakeList.ToArray());

//write string to file
System.IO.File.WriteAllText(@"path to file", json);

And on app start, you create your list initializing it from saved file. If file is not present, you just create empty list.

For that task you'd use JsonConvert.DeserializeObject method.

Look at Json.Net.

Related post

Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69