[[oktatas:programozás:csharp:dotnetcore|< .Net Core]]
====== Konfiguráció ======
* **Szerző:** Sallai András
* Copyright (c) 2024, Sallai András
* Szerkesztve: 2024
* Licenc: [[https://creativecommons.org/licenses/by-sa/4.0/|CC BY-SA 4.0]]
* Web: https://szit.hu
===== Függőség telepítése =====
dotnet add package Microsoft.Extensions.Configuration.Json
dotnet add package Microsoft.Extensions.Configuration.Binder
===== Konfig =====
{
"egy": "kettő"
}
===== Beolvasás =====
using Microsoft.Extensions.Configuration;
var builder = new ConfigurationBuilder();
builder
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", false);
var conf = builder.Build();
var a = conf.GetValue("egy");
Console.WriteLine(a);
Console.Read();
===== Felhasználók =====
{
"user": "janos",
"pass": "titok"
}
using Microsoft.Extensions.Configuration;
var builder = new ConfigurationBuilder();
builder.SetBasePath(Directory.GetCurrentDirectory());
builder.AddJsonFile("appsettings.json", false);
var conf = builder.Build();
var user = conf.GetValue("user");
var pass = conf.GetValue("pass");
Console.WriteLine(user + ":" + pass);
===== Objektum =====
{
"database": {
"user": "janos",
"pass": "titok"
}
}
using Microsoft.Extensions.Configuration;
var builder = new ConfigurationBuilder();
builder.SetBasePath(Directory.GetCurrentDirectory());
builder.AddJsonFile("appsettings.json", false);
var conf = builder.Build();
var user = conf.GetValue("database:user");
var pass = conf.GetValue("database:pass");
Console.WriteLine(user + ":" + pass);
===== Objektum másként =====
{
"database": {
"user": "janos",
"pass": "titok"
}
}
using Microsoft.Extensions.Configuration;
var builder = new ConfigurationBuilder();
builder.SetBasePath(Directory.GetCurrentDirectory());
builder.AddJsonFile("appsettings.json", false);
var conf = builder.Build();
var user = conf.GetSection("database").GetValue("user");
var pass = conf.GetSection("database").GetValue("pass");
Console.WriteLine(user + ":" + pass);
===== Láncolva egyszerűbben =====
{
"database": {
"user": "janos",
"pass": "titok"
}
}
using Microsoft.Extensions.Configuration;
var conf = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("config.json")
.Build();
var user = conf["database:user"];
var pass = conf["database:pass"];
Console.WriteLine(user + ":" + pass);