添加到保存在独立存储 WP 中的列表
本文关键字:WP 列表 存储 独立 保存 存在 添加 | 更新日期: 2023-09-27 18:34:06
im 尝试调用列表并使用
IsolatedStorageFile Settings1 = IsolatedStorageFile.GetUserStoreForApplication();
if (Settings1.FileExists("MyStoreItems"))
{
using (IsolatedStorageFileStream fileStream = Settings1.OpenFile("MyStoreItems", FileMode.Open))
{
DataContractSerializer serializer = new DataContractSerializer(typeof(MyDataList));
listobj = (PanoramaApp5.StorageControl.MyDataList)serializer.ReadObject(fileStream);
listobj.Add(new MyData { Name = filename, Location = ("/Downloaded/" + filename) });
serializer.WriteObject(fileStream, listobj);
}
}
我以前用过这个
listobj.Add(new MyData { Name = filename, Location = ("/Downloaded/" + filename) });
if (Settings1.FileExists("MyStoreItems"))
{
using (IsolatedStorageFileStream fileStream = Settings1.OpenFile("MyStoreItems", FileMode.Create))
{
DataContractSerializer serializer = new DataContractSerializer(typeof(MyDataList));
serializer.WriteObject(fileStream, listobj);
}
MessageBox.Show("Items stored successfully.");
}
它不断添加到列表中,直到我离开页面或关闭应用程序,如果再次调用,它只会重写列表。
如何在不破坏旧列表的情况下添加到列表中
编辑*
我使用以下代码写入列表
public static void writeisobtn_Click(string filename)
{
listobj.Add(new MyData { Name = filename });
using (IsolatedStorageFileStream fileStream = Settings1.OpenFile("MyStoreItems", FileMode.OpenOrCreate))
{
DataContractSerializer serializer = new DataContractSerializer(typeof(MyDataList));
serializer.WriteObject(fileStream, listobj);
}
MessageBox.Show("Items stored successfully.");
}
这工作正常,如果我使用 wptools 并获取文件并使用记事本++打开它,我会得到
<StorageControl.MyData><Name>TestName1</Name></StorageControl.MyData>
<StorageControl.MyData><Name>TestName2</Name></StorageControl.MyData>
我调用列表使用
using (IsolatedStorageFileStream fileStream = Settings1.OpenFile("MyStoreItems", FileMode.Open))
{
DataContractSerializer serializer = new DataContractSerializer(typeof(MyDataList));
listobj = (MyDataList)serializer.ReadObject(fileStream);
}
列表加载正常,我返回页面并向列表中添加更多名称,列表加载新名称 Aswel 作为旧名称,但是如果我关闭并打开应用程序,然后在我获取文件并打开它时添加 e.i TestName5 时,TestName5 只有一个条目
FileMode.Open,因为您的代码已经清楚地断言该文件存在。
using (IsolatedStorageFileStream fileStream = Settings1.OpenFile("MyStoreItems", FileMode.Open))
您也可以使用 (OpenOrCreate)
using (IsolatedStorageFileStream fileStream = Settings1.OpenFile("MyStoreItems", FileMode.OpenOrCreate))
然后,您不需要文件存在检查。
我像这样保存文件对其进行了排序
public static void writeisobtn_Click(string filename)
{
MyDataList listobj = new MyDataList();
using (IsolatedStorageFileStream fileStream = Settings1.OpenFile("MyStoreItems", FileMode.Open))
{
DataContractSerializer serializer = new DataContractSerializer(typeof(MyDataList));
listobj = (MyDataList)serializer.ReadObject(fileStream);
}
listobj.Add(new MyData { Name = filename });
using (IsolatedStorageFileStream fileStream = Settings1.OpenFile("MyStoreItems", FileMode.OpenOrCreate))
{
DataContractSerializer serializer = new DataContractSerializer(typeof(MyDataList));
serializer.WriteObject(fileStream, listobj);
}
MessageBox.Show("Items stored successfully.");
}