我想在我的 Windows Phone 8 应用程序中保存/恢复对象数据。对象是日志,每个日志都有自己的属性。日志的主列表名为 logArray。
然而,我不知道如何将保存的 .txt 文件转换回 logArray,以便在应用程序启动时备份!这是我的代码:
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());
}
}
最佳答案
也许您应该考虑使用 XML 或 JSON 等标记语言进行序列化和反序列化,然后将您的文本存储到文件中。
使用简单汽车对象的 XML 序列化示例:
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();
}
关于c# - 如何将字符串列表转换为现有对象列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23479976/