我正在尝试将一个列表(其中 Show 是我的实现 IXmlSerializable 的类)存储到本地隔离存储中。我正在使用此页面中的代码:http: //metrostoragehelper.codeplex.com/ 我已经实现了问题部分中建议的更改。当从项目列表中单击它时,我正在使用以下代码添加一个 Show 对象。
private async void addShowButton_Click_1(object sender, RoutedEventArgs e)
{
var isoStorage = new StorageHelper<List<Show>>(StorageType.Local);
List<Show> currentShows = await isoStorage.LoadASync("myShowsEx");
if(currentShows == null) {
currentShows = new List<Show>();
}
currentShows.Add(currentShow);
isoStorage.SaveASync(currentShows, "myShowsEx");
//Read it back, for debugging to check if it has been added properly.
List<Show> currentShowsRB = await isoStorage.LoadASync("myShowsEx"); //Exception here
}
第一个节目添加得非常好,它显示在 currentShowsRB 列表中。单击第二个项目并调用上述方法时,最后一次 LoadAsync 调用发生异常:访问被拒绝。(来自 HRESULT 的异常:0x80070005 (E_ACCESSDENIED))如何解决此问题以访问本地数据存储以进行多次调用?
下面也是来自 StorageHelper 的相关代码:
public async void SaveASync(T Obj, string FileName)
{
FileName = FileName + ".xml";
try
{
if (Obj != null)
{
StorageFile file = null;
StorageFolder folder = GetFolder(storageType);
file = await folder.CreateFileAsync(FileName, CreationCollisionOption.ReplaceExisting);
using (var writeStream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
Stream outStream = Task.Run(() => writeStream.AsStreamForWrite()).Result;
serializer.Serialize(outStream, Obj);
//writeStream.Dispose(); //Added and we get UnauthorizedAccessException
// outStream.Dispose(); //Added ObjectDisposedException caught in catch statement below
}
}
}
catch (Exception)
{
throw;
}
}
public async Task<T> LoadASync(string FileName)
{
FileName = FileName + ".xml";
try
{
StorageFile file = null;
StorageFolder folder = GetFolder(storageType);
file = await folder.GetFileAsync(FileName);
using (var readStream = await file.OpenAsync(FileAccessMode.Read))
{
Stream inStream = Task.Run(() => readStream.AsStreamForRead()).Result;
inStream.Position = 0;
return (T)serializer.Deserialize(inStream);
}
}
catch (FileNotFoundException)
{
//file not existing is perfectly valid so simply return the default
return default(T);
//throw;
}
catch (Exception)
{
//Unable to load contents of file
throw;
}
}
我添加了 writeStream.Dispose() 行,但即使包含此行,我也会收到相同的访问被拒绝的错误消息。如果我还包括 outStream.Dispose() 行,那么我会在下面的 catch 语句中捕获一个 ObjectDisposedException。还有什么我应该做的吗?