Search code examples
c#asp.net-core

IConfigurationBuilder.Build() fails with files starting with a dot


I have this piece of code to parse a config file:

var fullFilePath = @"c:\temp\.ext";
// var fullFilePath = @"c:\temp\my.ext"; // this one works
var builder = new ConfigurationBuilder().AddIniFile(fullFilePath).Build();

This code works when fullFilePath points to a file with some content and "normal" name like "C:\temp\my.ext".

However it fails when the file starts with a ., e.g. "C:\temp\.ext" (with identical content to the other one - copy c:\temp\me.ext c:\temp\.ext)

An exception thrown is during the .Build() which says

The configuration file '.ext' was not found and is not optional.

How do I parse config files that don't have a name, but only an extension?

Note that this code fails the same way from console app running under my account - while running it as asp.net may add more issues (as pointed in comments) this is not the case. Also files 100% exist and reproducible with absolute paths (as shown in MRE).


Solution

  • You can use AddIniStream instead (AddIniFile expects a valid path).

    https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.configuration.iniconfigurationextensions.addinistream?view=net-9.0-pp

    As an example:

    var fileContent = await File.ReadAllTextAsync("C:\\configurations\\.ext");
    using var memoryStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(fileContent));
    var config = new ConfigurationBuilder()
    .AddIniStream(memoryStream) 
    .Build();
    var dbServer = config["Database:Server"];