3

What I want
get a xml file from the AppData.Local, and serialize it to a list

What I code
The Error Part:

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

myTask is a simple class:

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

objectStorageHelper is a HelpClass from CodePlex, the LoadAsync part is below:

    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;
        }
    }

What is the Error

An exception of type 'System.UnauthorizedAccessException' occurred in mscorlib.dll but was not handled in user code

Additional information: Access Denied。 (Exception from HRESULT:0x80070005 (E_ACCESSDENIED))

If there is a handler for this exception, the program may be safely continued.

--
Why does this happen?
I can use this help class to successfully write to a file.
But Why don't I have the permission to read the file?
How to solve it?

Community
  • 1
  • 1
Albert Gao
  • 3,653
  • 6
  • 40
  • 69

2 Answers2

0

change

StorageFolder folder = GetFolder(storageType); 

to

StorageFolder folder = ApplicationData.Current.LocalFolder

if this works then the issue is with your folder permissions.

rob
  • 8,134
  • 8
  • 58
  • 68
0

change

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

to

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

or

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

and the same to the SaveAsync()