Skip to content

Instantly share code, notes, and snippets.

@pedroinfo
Last active March 18, 2025 16:50
Show Gist options
  • Save pedroinfo/5d015381e592b20ce48a200ef8a06414 to your computer and use it in GitHub Desktop.
Save pedroinfo/5d015381e592b20ce48a200ef8a06414 to your computer and use it in GitHub Desktop.
How to read App Settings in .net core without dependency
using System;
using System.IO;
using Newtonsoft.Json.Linq;
/// <summary>
/// Provides methods to retrieve connection strings and app settings from the appsettings.json file.
/// </summary>
public static class AppSettings
{
private static readonly Lazy<JObject> _config = new Lazy<JObject>(LoadAppSettings);
/// <summary>
/// Loads the appsettings.json file and parses it into a JObject.
/// </summary>
/// <returns>A JObject containing the configuration data.</returns>
private static JObject LoadAppSettings()
{
var basePath = AppDomain.CurrentDomain.BaseDirectory;
var configFilePath = Path.Combine(basePath, "appsettings.json");
if (!File.Exists(configFilePath))
{
throw new FileNotFoundException("The appsettings.json file was not found.", configFilePath);
}
var json = File.ReadAllText(configFilePath);
return JObject.Parse(json);
}
/// <summary>
/// Retrieves a connection string by its name.
/// </summary>
/// <param name="name">The name of the connection string.</param>
/// <returns>The connection string value.</returns>
public static string GetConnectionString(string name)
{
var connectionString = _config.Value["ConnectionStrings"]?[name]?.ToString();
if (string.IsNullOrEmpty(connectionString))
{
throw new ArgumentException($"Connection string '{name}' not found in appsettings.json.");
}
return connectionString;
}
/// <summary>
/// Retrieves an app setting by its key.
/// </summary>
/// <param name="key">The key of the app setting.</param>
/// <returns>The app setting value.</returns>
public static string GetAppSetting(string key)
{
var appSetting = _config.Value["AppSettings"]?[key]?.ToString();
if (string.IsNullOrEmpty(appSetting))
{
throw new ArgumentException($"App setting '{key}' not found in appsettings.json.");
}
return appSetting;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment