There are several ways to implement this, for example, json or text (*. txt).
Json
Install the package Json.NET, with the package manager Nuget:
After such installation you can from a structure, an object, etc. generate a json
of it and write to a file with the extension .json
Coding:
Serialize
//objeto criado
List<string[]> objListString = new List<string[]>();
objListString.Add(new string[] { "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 running this code, you will have a file inside the folder \bin
with the base.json name in this format:
Deserialize
To do the reverse process just read the file again and use JsonConvert.DeserializeObject
thus:
String dataJson = System.IO.File.ReadAllText(".\\base.json", Encoding.UTF8);
List<string[]> retorno = JsonConvert.DeserializeObject<List<string[]>>(dataJson);
Upshot
Text
Coding
To generate the same example in a file format .txt
it’s 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();
To generate the inverse txt process for an object in your program do:
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);
}
}
The two ways are viable alternatives, but if it were to choose would put in json.
Serialize the class and save to a file.
– Tony