I am wanting to save / restore object data in my Windows Phone 8 application. The objects are logs, each log having its own properties. The master list of logs is named logArray.
However the case, I do not know how to convert the saved .txt file back into the logArray, for when the app starts back up! Here is my code:
private async Task WriteToFile()
{
try
{
if (File.Exists("Logs.txt"))
{
File.Delete("Logs.txt");
}
StreamWriter write = new StreamWriter("Logs.txt");
//Write each log element to a new string line
foreach (Log element in logArray)
{
await write.WriteLineAsync();
}
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.ToString());
}
}
private async Task ReadFromFile()
{
try
{
//Variable definitions
StreamReader read = new StreamReader("Logs.txt");
List<String> lines = new List<String>();
String line;
if (File.Exists("Logs.txt"))
{
//Read each string line into a string list
while ((line = await read.ReadLineAsync()) != null)
{
lines.Add(line);
}
foreach (String element in lines)
{
//Convert String line to logArray object
}
}
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.ToString());
}
}
Perhaps you should consider serializing and de-serializing using a markup anguage like XML or JSON, and then storing your text to a file.
an example for XML serialization using a simple car object:
public static void WriteFile()
{
Car testCar= new Car();
string path = "c:\temp\testCarPath.xml";
XmlSerializer serializer = new XmlSerializer(typeof(Car));
StreamWriter file = new StreamWriter(path);
serializer.Serialize(file, testCar);
file.Close();
}
public static void ReadFile()
{
Car testCar;
string path = "c:\temp\testCarPath.xml";
XmlSerializer serializer = new XmlSerializer(typeof(Car));
StreamReader reader = new StreamReader(path);
testCar = (Car)serializer.Deserialize(reader);
reader.Close();
}