Getting File Path From Appsettings.json In Worker Service

We will discuss about getting data from app settings.json and how to use it in the class library. Here we have a DLL (Dynamic Link Library) or Class Library and Worker Service. In the file writing process, the file path must be declared in the configuration file. To declare a common detail, we need a config file. Not only file path, but we can also store Database configuration details in the appsettings.json file.

Create Worker service and Class library project and install the below mentioned packages from NuGet packages, 

  • Microsoft.Extensions.Configuration
  • Microsoft.Extensions.Configuration.Json
  • Microsoft.Extensions.Configuration.FileExtensions

Getting file path from appsettings.json in Worker Service

Worker Service will have an appsettings.json file. We can declare a file path and use the key value in the Class Library.

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "Path": {
    "LogFilePath": "C:\\Log\\"
  }
}

The file should be accessible all over the project. For that, we must change a property called "Copy to Output Directory" to Copy Always.

Getting file path from appsettings.json in Worker Service

The class Library code to get a file path key "LogFilePath" in appsetting. json

using Microsoft.Extensions.Configuration;
using System.IO;

namespace ClassLibrary
{
    public class Class1
    {
       
        public void method()
        {
           
           var builder = new ConfigurationBuilder()
                               .SetBasePath(Directory.GetCurrentDirectory())
                               .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

            string LogFilePath = builder.Build().GetSection("Path").GetSection("LogFilePath").Value;
            Console.WriteLine(LogFilePath);
            string logText = "Process started" + Environment.NewLine;
            if(LogFilePath != null)
                File.WriteAllText(LogFilePath + ".LOG", logText);

        } 
    }
}

Worker Service calls Class Library method,

using ClassLibrary; 
using static ClassLibrary.Class1;

namespace WorkerService
{
    public class Worker : BackgroundService
    {
        private readonly ILogger<Worker> _logger;

        public Worker(ILogger<Worker> logger)
        {
            _logger = logger;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            Class1 obj = new Class1();            
          
            while (!stoppingToken.IsCancellationRequested)
            {               
                obj.method();
                _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);                                
                await Task.Delay(1000, stoppingToken);                
            }
        }
       
    }
}

Output creating a Log file in the respective directory,

Getting file path from appsettings.json in Worker Service


Similar Articles