You are currently viewing Reading app.config file in a Xamarin.Forms Xaml project
Xamarin

Reading app.config file in a Xamarin.Forms Xaml project

Reading app.config file in a Xamarin.Forms Xaml project

If you are a C# developer, you may know about the App.config and Web.config and importance of the config file. You might have a question that Is Xamrin.Forms application also having App.config file?
The answer is no. in Xamarin application there is no App.config file with the project but you can create it manually and apply in the application.

Step 1: Create App.config file

How to add App.config file in Xamarin Project?

You need to create App.config file manually using a text editor like Notepad, Notepad++, Visual Studio etc. Here is the sample for App.config file.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="KEY1" value="VALUE1" />
<add key="KEY2" value="VALUE2" />
<add key="KEY3" value="VALUE3" />
<add key="KEY4" value="VALUE4" />
</appSettings>
</configuration>

Save the above text file as App.config

Now go to your Xamarin project =>Right Click on the Project => Add => Existing file => Select App.config file.

Step 2: Set App.config file build action

Right-click on the App.config file => Properties => Build Action
For Android set Build Action to ‘AndroidAsset’
For UWP set Build Action to ‘Content’

Step 3: Add NuGet package reference

Add the NuGet package reference to your PCL and platforms projects.
Here is the link for Nuget package: https://www.nuget.org/packages/PCLAppConfig

You can add new Nuget package or install using NuGet Package Manager Console

PM> Install-Package PCLAppConfig -Version 1.0.1

Step 4: Initialize ConfigurationManager.AppSettings

Initialize ConfigurationManager.AppSettings on each of your platform project, just after the ‘Xamarin.Forms.Forms.Init’ statement, as per below:

For iOS (AppDelegate.cs)

global::Xamarin.Forms.Forms.Init();
ConfigurationManager.Initialise(PCLAppConfig.FileSystemStream.PortableStream.Current);
LoadApplication(new App());

For Android (MainActivity.cs)

global::Xamarin.Forms.Forms.Init(this, bundle);
ConfigurationManager.Initialise(PCLAppConfig.FileSystemStream.PortableStream.Current);
LoadApplication(new App());

For UWP

Xamarin.Forms.Forms.Init(e);
ConfigurationManager.Initialise(PCLAppConfig.FileSystemStream.PortableStream.Current);

For Xamarin.Android Project (MainActivity.cs)

base.OnCreate(savedInstanceState);
ConfigurationManager.Initialise(PCLAppConfig.FileSystemStream.PortableStream.Current);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.activity_main);

Step 5: Read your settings

You can read your setting value using ConfigurationManager.AppSettings[“KEY”]
replace KEY with the key name from App.config file.

That’s all done.