ConfigurationManager and AppSettings in universal (UWP) app

Amadeusz Wieczorek picture Amadeusz Wieczorek · Jan 15, 2016 · Viewed 18k times · Source

I would like to store an API key in a configuration file without checking it into source control, and read the data in my UWP app.

A common solution is to store the key in .config file (such as app.config or web.config) and access it like so:

var apiKey = ConfigurationManager.AppSettings.Get("apiKey");

I'm working on a Universal Windows (UWP) app and can't access the System.Configuration namespace that holds ConfigurationManager.

How can I access AppSettings in UWP app? Alternatively, what's the best way to access configuration data in an UWP app?

Answer

Amadeusz Wieczorek picture Amadeusz Wieczorek · Jan 23, 2016

In my specific use case I needed to use an external file that is not tracked by source control. There are two ways to access data from resource or configuration files.

One is to open and parse a configuration file. Given a file sample.txt with Build Action Content (Copy to Output Directory doesn't matter), we can read it with

var uri = new System.Uri("ms-appx:///sample.txt");
var sampleFile = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(uri);

or

var packageFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;
var sampleFile = await packageFolder.GetFileAsync("sample.txt");

followed by

var contents = await Windows.Storage.FileIO.ReadTextAsync(sampleFile);

Alternatively, we can use Resources. Add a new Resource item to the project, called resourcesFile.resw. To access data, use:

var resources = new Windows.ApplicationModel.Resources.ResourceLoader("resourcesFile");
var token = resources.GetString("secret");

I wrote more verbose answer in a blog post Custom resource files in UWP