为什么我不能在WinRT中从AppData读取XML?

时间:2012-06-16 12:50:22

标签: c# xml windows-8 windows-runtime microsoft-metro

我想要什么
从AppData.Local获取一个xml文件,并将其序列化为一个列表

我的代码
错误部分:

List<myTask> AllTaskList = await  objectStorageHelper.LoadAsync();

myTask是一个简单的类:

public class myTask
{
    public string myTitle { get; set; }
    public string myDuetime { get; set; }
}

objectStorageHelper是来自CodePlex的HelpClass,LoadAsync部分位于以下位置:

    public async Task<T> LoadAsync()
    {
        try
        {
            StorageFile file = null;
            StorageFolder folder = GetFolder(storageType);
            file = await folder.GetFileAsync(FileName());
            //file = await folder.CreateFileAsync("BetterTask.xml", CreationCollisionOption.OpenIfExists);
            IRandomAccessStream readStream = await file.OpenAsync(FileAccessMode.Read);
            Stream inStream = Task.Run(() => readStream.AsStreamForRead()).Result;
            return (T)serializer.Deserialize(inStream);
        }
        catch (FileNotFoundException)
        {
            //file not existing is perfectly valid so simply return the default 
            return default(T);
            //Interesting thread here: How to detect if a file exists (http://social.msdn.microsoft.com/Forums/en-US/winappswithcsharp/thread/1eb71a80-c59c-4146-aeb6-fefd69f4b4bb)
            //throw;
        }
        catch (Exception)
        {
            //Unable to load contents of file
            throw;
        }
    }

错误是什么

  

mscorlib.dll中发生了'System.UnauthorizedAccessException'类型的异常,但未在用户代码中处理

     

附加信息:访问被拒绝。(HRESULT异常:0x80070005(E_ACCESSDENIED))

     

如果存在此异常的处理程序,则可以安全地继续该程序。

-
为什么会这样? 我可以使用此帮助类成功写入文件 但为什么我没有阅读文件的权限呢? 怎么解决?

2 个答案:

答案 0 :(得分:0)

变化

StorageFolder folder = GetFolder(storageType); 

StorageFolder folder = ApplicationData.Current.LocalFolder

如果这样可行,则问题在于您的文件夹权限。

答案 1 :(得分:0)

变化

 Stream inStream = Task.Run(() => readStream.AsStreamForRead()).Result;
 return (T)serializer.Deserialize(inStream);

using (Stream inStream = Task.Run(() => readStream.AsStreamForRead()).Result)
{
    return (T)this.xmlSerializer.Deserialize(inStream);
}

inStream.Flush();
inStream.Dispose();

和SaveAsync()

相同