How to get a file using WinRT?

2019-02-27 21:41发布

What I want:
get a xml from the AppData to use

What I code

   StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
   StorageFile sampleFile = localFolder.GetFileAsync("abc.xml");

What I get
Error: Cannot implicitly convert type 'Windows.Foundation.IAsyncOperation' to 'Windows.Storage.StorageFile'

What I Check

When this method completes successfully, it returns a StorageFile that represents the file.

from MSDN

What I have
Windows 8 Release Preview 64bit;
Visual Studio Express 2012 RC for Windows 8;
C#

I write the code according to the MSDN doc, Why does this error happen and how to resolve it?

2条回答
你好瞎i
2楼-- · 2019-02-27 22:02

Try using "StorageFile sampleFile = await localFolder.GetFileAsync("abc.xml")" if you're in C# or "localFolder.GetFileAsnc("abc.xml").done(function (sampleFile) {})" if you're using JS.

查看更多
祖国的老花朵
3楼-- · 2019-02-27 22:15

Larry gave you the right solution. Let me try to explain what was going on.

If you look at the MSDN documentation for GetFileAsync, you will see that it returns an IAsyncOperation. Your code assumes that it returns a SampleFile. GetFileAsync doesn't provide a file, it provides an object which will provide a file once the retrival is complete.

Await in C# provides a function that will be called by that object (or on behalf of that object) once the conditions for completion are satisfied. That function then returns the value to you. A promise in JavaScript (.then or .done) provides similar functionality, but you have to supply the function yourself.

The reason for this is so that the application can be responsive. File access is slow. If accessing memory took 1 second, then file access would take about 15 minutes. Asynchronous programming allows other things to happen while your program is waiting.

查看更多
登录 后发表回答