Any method to save the data of an ArrayList

2

First of all, some information:

  .NET Framework 4.0 Visual C # = =

I am simulating a database using a class specifically for this, using a List<string[]> , however, I would like to be able to store and save this data even after closing the program, a solution like generating a .txt file and when the application starts, read that file and write the data that is in it, in List<string[]> .

If there is no more practical solution (in addition to using a database, in fact), I would like to know how to generate this .txt file and how it could make the application read it, if there is a more practical solution, what it would be and how it could be put into practice.

    
asked by anonymous 26.04.2014 / 02:12

2 answers

2

There are several ways to implement this, for example or text (* .txt).

Json

Install the Json.NET package with the package manager NuGet :

Aftersuchinstallationyoucanfromastructure,anobject,etc.generateajsonofitandwritetoafilewiththeextension.json

Encoding:

Serialize

//objetocriadoList<string[]>objListString=newList<string[]>();objListString.Add(newstring[]{"1", "valor 1" });
objListString.Add(new string[] { "2", "valor 2" });
objListString.Add(new string[] { "3", "valor 3" });

//serializando objeto no formato Json
var data = JsonConvert.SerializeObject(objListString);

//gravando informação em um arquivo na pasta raiz do executavel
System.IO.StreamWriter writerJson = System.IO.File.CreateText(".\base.json");
writerJson.Write(data);
writerJson.Flush();
writerJson.Dispose();

After executing this code, you will have a file inside the \bin folder named base.json in this format:

Deserialize

TodothereverseprocessjustreadthefileagainanduseJsonConvert.DeserializeObjectthisway:

StringdataJson=System.IO.File.ReadAllText(".\base.json", Encoding.UTF8);
List<string[]> retorno = JsonConvert.DeserializeObject<List<string[]>>(dataJson);

Result

Text

Coding

To generate the same example in the format of a .txt file is simple, note code:

System.IO.StreamWriter writerTxt = System.IO.File.CreateText(".\base.txt");
foreach(string[] item in objListString.ToArray())
{
     writerTxt.WriteLine(String.Join(";", item));
}
writerTxt.Flush();
writerTxt.Dispose();

Togeneratetheinversetxtprocessforanobjectinyourprogramdo

String[]dataTxt=System.IO.File.ReadAllLines(".\base.txt", Encoding.UTF8);
foreach (String linha in dataTxt)
{
      String[] itens = linha.Split(';');
      if (itens.Count() > 0)
      {
         objListString.Add(itens);
      }
}

Bothwaysareviablealternatives,butifIweretochooseIwouldput json .

    
26.04.2014 / 17:03
2

You can serialize the object to JSON , save to a file, then read the file and deserialize the string using Json. net .

string json = JsonConvert.SerializeObject(objeto);
List<string[]> objeto = JsonConvert.DeserializeObject<List<string[]>>(json);
    
26.04.2014 / 04:14