Skip to content

Configuration - Invalid file paths #24555

@saluton-mundo

Description

@saluton-mundo

To reproduce create a pfx file and add it your machine. Make a note of where you hold it on the file system.

For simplicity I just created a Test.pfx within a directory named "Test" on my machine's D drive. I inspected the directory permissions and made sure the read access is permitted. I opened a new Project targeting Core 2.0.1 with Visual Studio 2017 running as administrator (full env details at the end)

Add a section to your config file (appsetting-{env}.json as follows:

"CertificateConfig": { "CertificatePath":"D:\\Test\\test.pfx", "CertificatePassword":"secret" }

Create a strongly typed POCO CertificateConfig.cs with a public string property named "CertificatePath" with get/set. Another property for the password in the same way.

Then in your Startup.cs do the necessary Configuration binding to IOptions as follows:

services.Configure<CertificateConfig>(options => Configuration.GetSection("CertificateConfig").Bind(options));

Don't forget to add the services.AddOptions(); to Startup.cs within void ConfigureServices(IServiceCollection services) method.

Now create a simple Controller (or a method within a separate service layer etc) and inject the IOptions<CertificateConfig> config into the constructor.

Now if you did the following:

X509Certificate2 certificate = new X509Certificate2(config.Value.CertificatePath, config.Value.CertificatePassword);

you should get an exception saying the file path is invalid.

How are you meant to store file paths within the JSON config files?

If I hard code a string as follows:

string path = @"D:\Test\test.pfx";

it works flawlessly.

The same result is present if you use File.Open or try to pass a FileInfo object instead of a filepath.

I can't use \ as a value within a json config file and / would result in an equally invalid file path.

I get that Core is meant to be OS agnostic but how can supply a file path in a config which satisfies the separator without using Path.DirectorySeparatorChar

Any help would be appreciated.

ENVIRONMENT

Microsoft Visual Studio Community 2017
Version 15.5.2
VisualStudio.15.Release/15.5.2+27130.2010
Microsoft .NET Framework
Version 4.6.01038
assemblyref://Microsoft.NETCore.App (2.0)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions