2 回答
TA贡献1804条经验 获得超3个赞
尝试使用 File.AppendAllText 而不是 File.WriteAllText,因为 WriteAllText 会在写入时覆盖现有文件。
public void CreateListOfObjects()
{
string fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "history.txt");
var content = File.ReadAllText(fileName);
var itemList = JsonConvert.DeserializeObject<List<string>>(content);
foreach(var item in itemList)
{
listView2.Items.Add(item);
}
}
TA贡献1804条经验 获得超2个赞
我终于找到了解决方法。现在我首先使用一个 List 来为我的对象数组提供包装器。
// ListView A (Source)
// when ItemSelected is processed this function is called
public void AddToHistory(Object obj)
{
string fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "history.txt");
var _tempList = new List<Object>();
if (File.Exist(fileName)
{
var _tempContent = File.ReadAllText(fileName);
var json = JsonConvert.DeserializeObject<List<Object>>(tempContent);
_tempList.AddRange(json);
_tempList.Add(obj);
} else
{
_tempList.Add(obj);
}
var content = JsonConvert.SerializeObject(_tempList);
File.WriteAllText(fileName, content);
}
// ListView B (Destination View)
void CreateListOfObjects()
{
ObjectList = new List<Object>();
string fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "history.txt");
var content = File.ReadAllText(fileName);
var json = JsonConvert.DeserializeObject<List<Object>>(content);
ObjectList.AddRange(json);
}
- 2 回答
- 0 关注
- 97 浏览
添加回答
举报