Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ConfigurationManager and AppSettings in universal (UWP) app

Tags:

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?

like image 235
Amadeusz Wieczorek Avatar asked Jan 15 '16 02:01

Amadeusz Wieczorek


People also ask

What is ConfigurationManager AppSettings?

it is a .net builtin mechanism to define some settings before the application starts, without recompiling. see msdn configurationmanager.

What is the use of ConfigurationManager in C#?

The ConfigurationManager class enables you to access machine, application, and user configuration information. This class replaces the ConfigurationSettings class, which is deprecated. For web applications, use the WebConfigurationManager class.


1 Answers

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

like image 99
Amadeusz Wieczorek Avatar answered Sep 20 '22 15:09

Amadeusz Wieczorek