17

I want to store development vs production connection strings and configuration strings in a monodroid project. I would normally store it as app settings in a web.config or an app.config, but how should I do it in monodroid and monotouch projects? I would also like for it to switch configurations automatically between debug and release builds just as visual studio does with *.config files. In an iOS app I could store these in a plist but I'd like a cross platform solution in mono.

How would I do this in monodroid or monotouch?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
MonkeyBonkey
  • 46,433
  • 78
  • 254
  • 460

2 Answers2

21

You should just use a static class with #if declarations.

Something like:

public static class Configuration {
#if DEBUG
    public const string ConnectionString = "debug string";
#else
    public const string ConnectionString = "release string";
#endif
}

The benefit to using app.config is the ability to change these settings on the file system without recompiling. On mobile, there isn't a good way (especially on iOS) to edit the file after it's deployed. So it's generally better to just use a static class and redeploy when you need to change the values. This will also work on all platforms, because it is just C# code doing the work.

jonathanpeppers
  • 26,115
  • 21
  • 99
  • 182
  • If your going to do that then using an xcconfig is better than cluttering up the code with global variables. And technically, it' – Nick Turner Apr 25 '14 at 14:12
  • 1
    Does Xamarin support xcconfing? I have never seen it used. It definitely isn't something that works on Android either. The asker is wanting a cross-platform solution. – jonathanpeppers Apr 25 '14 at 14:50
  • This still seems to be the best option for handling these situations. – Jammer May 19 '15 at 11:25
6

there's a Xamarin centric AppSetting reader available at https://www.nuget.org/packages/PCLAppConfig it is pretty useful for continuous delivery;

use as per below:

1) Add the nuget package reference to your pcl and platforms projects.

2) Add a app.config file on your PCL project, then as a linked file on all your platform projects. For android, make sure to set the build action to 'AndroidAsset', for UWP set the build action to 'Content'. Add you settings keys/values: <add key="config.text" value="hello from app.settings!" />

3) Initialize the ConfigurationManager.AppSettings on each of your platform project, just after the 'Xamarin.Forms.Forms.Init' statement, that's on AppDelegate in iOS, MainActivity.cs in Android, App in UWP/Windows 8.1/WP 8.1:

ConfigurationManager.Initialise(PCLAppConfig.FileSystemStream.PortableStream.Current);

3) Read your settings : ConfigurationManager.AppSettings["config.text"];