Get Local Folders from App WinRT

2019-02-15 13:31发布

问题:

I'm having an issue trying to save a file into a folder of the WinRT app I'm working at. More specific : I can't manage to retrieve the folder. I need to save some files and afterwards to retrieve them from that same folder, let's say MyFolder which is actually at the same level in the app with the Assets folder. How can I achieve such thing?

So far I tried

await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("MyFolder")

and

await ApplicationData.Current.LocalFolder.GetFolderAsync("MyFolder");

and both seem to tell me that such folder doesn't exist. Now, I can't seem to figure it out if I'm on the right track or it's something foolish I've done and causes that exception. I can't really post the whole code, because it's actually a call to a larger method with other calls, and so on.

Also, I'd like to know (if any of these methods are correct), if the app gets an update, the content is affected in any way (better said, lost).

Thank you.

回答1:

Windows.ApplicationModel.Package.Current.InstalledLocation will give you the 'file system' defined by the application package, so you'd see you the commonly used Asset folder, for instance, via the URI ms-appx:///Assets Anything accessed via InstalledLocation or the ms-appx scheme is read-only because it's defined by the project you deployed from Visual Studio.

ApplicationData.Current.LocalFolder allows you to access the 'file system' owned by the current application/user (and stored at %AppData%/Local/Packages/<yourapppackage>/LocalState). You can create whatever structure you want here to manage your various roles, and use the ms-appdata:///local/DirLeve1/DirLeve2/File3 URI to access your files). That storage is retained through updates to your application, though, of course, you'll need a strategy for updating whatever stored data formats are required to interact with the newer version of your application.

It sounds like you're assuming LocalFolder cannot contain a folder hiearachy; it can, and so you could have a Recents subfolder for instance under the LocalFolder reference and handle things that way.



回答2:

I think you need to use the ms-appx URI. Something like this:

await StorageFolder.GetFolderFromPathAsync("ms-appx:///MyFolder");

Also, you need to make sure that the folder is actually getting included in the output. I'm not exactly sure how you do this in C# projects -- in C++ it's by setting the folder/file's "Is Content" build property to true.