user6115111
user6115111

Reputation: 41

Read an xml file from app data in a UWP app

We have a UWP app. I want to parse an XML file that will be placed into the add data for the app, by another app. (our app isn't being uploaded to the store, so we are able to do this).

What is the best way for me to open this file from my UWP app? Can I just read it like this?

StorageFile file =await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///" + xmlfile.xml));

I believe the XML file will be placed in a location such as c:\users\[user]\AppData....

thanks

Upvotes: 1

Views: 1410

Answers (1)

Martin Zikmund
Martin Zikmund

Reputation: 39082

You should save the file in the LocalState or TempState subfolder of the app's package folder in AppData\Local\Packages (depending on what is the purpose of the file - persistent or just temporary).

Now you have two options to access the file:

Using ApplicationData class

You can access the LocalState folder using:

var folder = ApplicationData.Current.LocalFolder;

and the TempState folder using:

var folder = ApplicationData.Current.TemporaryFolder;

Now, both these folder are normal instances of StorageFolder, so to get your file, you can just call:

var yourFile = await folder.GetFileAsync( yourFileName );

Using Application URI

Alternatively you can use special application URIs to access the file. Both folders I have mentioned have special URIs assigned.

The LocalState folder can be accessed using the following URI:

ms-appdata:///local/

And the TempState folder using:

ms-appdata:///temp/

This means you can use the following to get your file from LocalState folder:

var file = await StorageFile.GetFileFromApplicationUriAsync(
   new Uri("ms-appdata:///local/" + yourFileName) );

Note about the publisher cache folder

There is a third location you could use to share the files between your apps. Because they come from the same publisher, you can use the Publisher cache folder to store and read files. More information can be found in this useful blogpost by Microsoft.

Upvotes: 2

Related Questions