Skip to content

Instantly share code, notes, and snippets.

@ruyut
Created Dec 27, 2021
Embed
What would you like to do?
C# json settings read and write example
using System;
using System.IO;
using Newtonsoft.Json;
namespace RuyutConsoleApp
{
internal class Program
{
private static void Main(string[] args)
{
ReadConfiguration();
Console.WriteLine(Data.Name);
Console.WriteLine(Data.Blog);
Console.WriteLine(Data.Car);
Data.Name = "Ruyut";
Data.Blog = "https://www.ruyut.com";
Data.Car = 0;
SaveConfiguration();
}
public class ConfigurationDto
{
public string Name;
public string Blog;
public int Car;
}
public static ConfigurationDto Data = new();
public static string FilePath = "RuyutConsoleApp.json";
public static void ReadConfiguration()
{
if (!File.Exists(FilePath)) File.WriteAllText(FilePath, JsonConvert.SerializeObject(Data));
var fileData = File.ReadAllText(FilePath);
try
{
JsonConvert.PopulateObject(fileData, Data);
}
catch (Exception e)
{
Console.WriteLine("設定檔內容有誤,請確認!\n" + e.Message, "設定檔內容有誤");
}
}
public static void SaveConfiguration()
{
string output = JsonConvert.SerializeObject(Data);
File.WriteAllText(FilePath, output);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment