1

Ok, so let me take a simple example of what I'm trying to describe. This is probably a very "n00b" question, and yet I've ready plenty of programming books and they never have examples like this.

Let's say I have a program like

public class Program
{
   private static List<string> _input = new List<string>(); 

   public static void Main()
   {
       string line; 
       while((line = Console.ReadLine()) != null)
       {
            Program._input.Add(line);
       }  
       return 0;            
   }
}

except want to modify it so that the next time I launch, the lines I added to input the previous time I ran the program are still there. Is there a way to do this (without writing the list to a text file or something like that)? If so, how?

user6048670
  • 2,861
  • 4
  • 16
  • 20
  • It's going to have to be written somewhere. You could store it in settings (which writes it to a file in your Windows profile behind the scenes). Have a look at [How to save a List on Settings.Default?](http://stackoverflow.com/questions/2890271/how-to-save-a-liststring-on-settings-default). – Tone Jun 28 '16 at 02:45
  • The list must be stored somewhere, so if file is not an option, registry/database/cloud? – Shane Lu Jun 28 '16 at 02:45
  • You can serialize your list. [see example here](http://www.dotnetperls.com/serialize-list) – Muhammad Yaseen Khan Jun 29 '16 at 11:22

4 Answers4

1

Once your application is closed, everything stored in variables is lost when your application is destroyed.

The only way to persist data is to store it somewhere outside of your program. The most common are files or databases. In your case, you're just storing lines of text so I'd probably go with a file.

You can easily write to the file when the application is closing and then read from the file when the application starts.

Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
0

If you want save all value of your class you can use a Serialization

you can have some example here : Examples of XML Serialization

But in all case you need to write in a file you can keep it in RAM.

Franckentien
  • 324
  • 6
  • 21
  • Why are you recommending XML Serialization for lines of plain text? And storing in RAM tends to just prolong the issue of permanence, perhaps a NOT is missing. – Glenn Teitelbaum Jun 28 '16 at 13:41
0

Whenever you close your program, Windows frees memory. Only files are preserved.

Writing file is not evil but just one simple statement.

File.WriteAllLines("lines.txt", _input);

Reading file is also easy.

_input.AddRange(File.ReadAllLines("lines.txt"));
Tommy
  • 3,044
  • 1
  • 14
  • 13
0

When application is closed on operating system, it is taken out from the computer memory...so you have to save its state to some kind of file or storage devices... as far as I concern that is the only way

June
  • 974
  • 5
  • 20
  • 34