0

I am converting my Xamarin Forms Application to .NET MAUI.

In existing application I am using below code which is using Xamarin.iOS to fetch the config file(App.config) which is in xml format and has app settings

public string Path
        {
            get
            {
                try
                {
                    return System.AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
                }
                catch
                {
                    throw new FileNotFoundException(@"File not found.");
                }
            }
        }

But the same code doesn't work in MAUI

I tried below approach but File.OpenRead(Path) is throwing error "Data at the root level is invalid. Line 1, position 1" App.config file is added in path Projectname/Platforms/iOS/App.config

public string Path
        {
            get
            {
                try
                {
                    string configPath = string.Empty;
                    configPath = Assembly.GetEntryAssembly().Location + ".config";
                    AppDomain domain = System.AppDomain.CurrentDomain;
                    configPath = System.IO.Path.Combine(domain.SetupInformation.ApplicationBase, domain.FriendlyName + ".config");
                    return configPath;
                }
                catch
                {
                    throw new FileNotFoundException(@"File not found.");
                }
            }
        }

Any help is appreciated!

Mars
  • 269
  • 1
  • 3
  • 22
  • *Which line of code* throws that error? – ToolmakerSteve Nov 10 '22 at 21:52
  • File.OpenRead(Path) is throwing the error – Mars Nov 11 '22 at 04:03
  • That is an `XML` error message, not a `System.IO.File.OpenRead` error message. What is the value of `Path`? Show several lines of code before and after `File.OpenRead`. Most importantly, show code that is trying to work with xml. Maybe it found an empty file? But that still would fail on a different line. Sounds like your source file isn't identical to what is executing - Rebuild Solution. – ToolmakerSteve Nov 11 '22 at 20:22

1 Answers1

0

Since the value of Path could be obtained, you could manually checked the content to see if it is the one you want.

From the thrown error "Data at the root level is invalid. Line 1, position 1", it seems something wrong with xml data load. Some issues similar to this question indicated that it may due to BOM character, take a look at this issue.

Actually we could use appsettings.json as an alternative, see this App Configuration Settings in .NET MAUI and github project. It's really easy to read app config in this way.

Liqun Shen-MSFT
  • 3,490
  • 2
  • 3
  • 11