ConfigurationManager and AppSettings in universal (UWP) app
Asked Answered
G

4

24

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?

Globoid answered 15/1, 2016 at 2:54 Comment(2)
Can you add System.Configuration as reference?Ambivert
No, it's not available as a reference gyazo.com/b1a6d73eb324397be66b4d38b68dd964 nor in object browserGloboid
G
19

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

Globoid answered 23/1, 2016 at 20:54 Comment(4)
I don't see though how this solves the without checking it into source control requirement, as you will need to add a file to the project to set it's Build Action, thus making it quite cumbersome to exclude from the source control.Disgusting
@GabrielRainha that's not an actual requirement of the question -- if you read it carefully, you'll see that the OP has specified that he already has a way of doing this when using app.config files. -- Hence, he just needs to know what to use instead of app.config files. -- It's a shame he didn't share his method with us though.Tegular
I had a problem with a file not found exception with my .json file at the root of the app, so I followed what it says there: File Not Found Exception in Universal Windows PlatformNavaho
What is the point of storing in a text file not tracked by source control?? After your app is deployed anybody can go to the installation folder and view everything, if you aren't serious about protecting your keys why not just include the text file in source control to save yourself from some pain.Sparky
J
2

It's an old question, but here my solution :

  • Create a partial class Config.cs (for example) with all the properties you'r needed
  • Add a partial method void Init()
  • Call Init in the constructor
  • Create an other file Config.partial.cs with the void Init() method filling all your properties

-> Use #if DEBUG / #else / #endif to switch from Debug/Release -> Use exclude Config.partial.cs from Github to not import it in the repository

Now it compile and it's not in the repository Alternatively you can set in Config.cs default (not secret) datas.

Config.cs :

public partial class Config
{

  public Config()
  {
      Init();
  }

  partial void Init();

  public string ApiKey{ get; private set; }= "DefaultValueAPIKEY";
}

Config.partial.cs

public partial class Config 
{

  partial void Init()
  {
#if DEBUG

    this.ApiKey = "DebugAPIKEY";

#else

    this.ApiKey = "ReleaseAPIKEY";

#endif
  }
}
Jolinejoliotcurie answered 19/8, 2019 at 14:46 Comment(0)
G
0

I'm thinking that what you call "ApiKey" is the static key that an API gives you to generate an access token. If this is the case, maybe the best way to achieve this is to create a static class out of the source control with that value inside of it, something like this:

public static class MyCredentials
{
    public static string MyApiKey = "apiKey";
}

Then you access that value easily from your code:

var myApiKey = MyCredentials.MyApiKey;

If you want to store values in a plain-text file instead you will have to write/read it manually using StorageFile and FileIO classes.

Instead, if "ApiKey" means the dynamic access token, then the best solution is use ApplicationDataContainer as stratever says.

Guatemala answered 15/1, 2016 at 11:18 Comment(1)
Thank you @garolad for your suggestion on using FileIO class. I posted an answer that uses this class.Globoid
C
-2

You don't need to create a configuration file. UWP has a built-in solution to store local settings/configurations. Please check this tutorial:

https://msdn.microsoft.com/en-us/library/windows/apps/mt299098.aspx

Using ApplicationDataContainer, you will be able to get a value by key:

Object value = localSettings.Values["exampleSetting"];
Conservative answered 15/1, 2016 at 10:10 Comment(2)
Thank you @stratever. This would work if I wanted to read data that is created on runtime. I need to use data that's bundled with the application (but not checked into source control)Globoid
@Conservative - this isn't meant for app configuration data - it's more for things like user preferencesMezzorelievo

© 2022 - 2024 — McMap. All rights reserved.