简体   繁体   中英

Read file located in class library

I have a project containing just a class library. The project is later going to be used as a nuget package.

In the class library, I have a settings.json where I have my connectionString. But I don't know how to read the file?

I have tried to do like this:

public static class Injections
{
    public static IServiceCollection AddServiceAndRoleSecurity(this IServiceCollection services)
    {
        builder.AddJsonFile("settings.json");
        var Configuration = builder.Build();
    }
}

The settings.json is in the same folder as the Injections.cs, but this don't work.

However, it works if I use the full path to the file:

public static class Injections
{
    public static IServiceCollection AddServiceAndRoleSecurity(this IServiceCollection services)
    {
        //Works
        builder.AddJsonFile(@"C:\Projects\classlibs\Security\Application\Configuration\settings.json");
        var Configuration = builder.Build();
    }
}

But I don't want to use the full path.

If your intent to add a separate settings.json file is to allow end user to update connectionstring, which willbe used in your class library(evantually NuGet package).

Then I'd suggest you to create a parameterized constructor/method in your class library, which takes connectionstring as a parameter from user.

This way user will have freedom to save connectionstring to wherever they want like web.config/app.config/hard-coded...

Example -

public MyNuGetPackage
{
    public MyNuGetPackage(string connectionString)
    {
        //use it wherever you want
    }

    -- OR --

    public SetConnectionString(string connectionString)
    {
        //use it wherever you want
    }

}

Then, end user can use your package as -

var obj = new MyNuGetPackage(ConfigurationManager.AppSettings["MyConnectionString"]);

-- OR --

var obj = new MyNuGetPackage();
obj.SetConnectionString(ConfigurationManager.AppSettings["MyConnectionString"]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM