当我尝试在 Windows Phone 上保存列表时,我收到“System.UnauthorizedAccessException:访问被拒绝。”消息。
设想:
当点击收藏按钮时,系统将检查该项目是否已经收藏。
下一步是调用 Load 方法。这将返回一个包含收藏夹的列表。
当该项目被收藏时,我会将其从列表中删除,否则我将添加它。
最后一步是使用我的 Save 方法保存新列表。
执行此代码时,我得到以下异常:
System.UnauthorizedAccessException:访问被拒绝。(来自 HRESULT 的异常:0x80070005(E_ACCESSDENIED
我环顾四周,发现它可能是清单功能。所以我已经检查了所有这些只是为了确定。再次尝试后,我仍然得到异常!
我必须做什么?下面的代码:
private async void favoriteClicked(object sender, EventArgs e)
{
if (_progressIndicator.IsVisible == false)
{
try
{
Boolean isFavorite = Settings.GetValueOrDefault<Boolean>(currentArtist.id, false);
ArtistSaving favorite = new ArtistSaving(currentArtist.id, currentArtist.name, currentArtist.shortBio);
artistList = await Task.Run(() => Utils.Load<ArtistSaving>());
if (isFavorite == true)
{
artistList.Remove(favorite);
displayDeletePopup();
Settings.AddOrUpdateValue(currentArtist.id, false);
await Task.Run(() => Utils.Save<ArtistSaving>(artistList));
}
else
{
artistList.Add(favorite);
displayXamlPopup();
Settings.AddOrUpdateValue(currentArtist.id, true);
await Task.Run(() => Utils.Save<ArtistSaving>(artistList));
}
}
catch (ArgumentException ex)
{
}
}
}
收藏按钮点击
public static async Task<ObservableCollection<T>> Load<T>()
{
// Create a new folder name DataFolder.
var file = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync(JSONFILENAME,
CreationCollisionOption.OpenIfExists);
var jsonSerializer = new DataContractJsonSerializer(typeof(ObservableCollection<T>));
var myStream = await file.OpenStreamForReadAsync();
ObservableCollection<T> myObj = (ObservableCollection<T>)jsonSerializer.ReadObject(myStream);
if (myObj == null)
{
return new ObservableCollection<T>();
}
return myObj;
}
这是加载方法
public static async void Save<T>(ObservableCollection<T> obj)
{
var serializer = new DataContractJsonSerializer(typeof(ObservableCollection<T>));
using (var stream = await ApplicationData.Current.LocalFolder.OpenStreamForWriteAsync(
JSONFILENAME, CreationCollisionOption.ReplaceExisting))
{
serializer.WriteObject(stream, obj);
}
}
这就是 Save 方法
编辑——解决方案
public static async Task<ObservableCollection<T>> Load<T>()
{
ObservableCollection<T> myObj = null;
// Create a new folder name DataFolder.
var file = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync(JSONFILENAME,
CreationCollisionOption.OpenIfExists);
var jsonSerializer = new DataContractJsonSerializer(typeof(ObservableCollection<T>));
using (var myStream = await file.OpenStreamForReadAsync())
{
myObj = (ObservableCollection<T>)jsonSerializer.ReadObject(myStream);
if (myObj == null)
{
return new ObservableCollection<T>();
}
return myObj;
}
}