Skip to content

Instantly share code, notes, and snippets.

Created December 27, 2021 14:39
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save ruyut/084226e2ffcc88f1ca505048631b8405 to your computer and use it in GitHub Desktop.
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)
Data.Name = "Ruyut";
Data.Blog = "";
Data.Car = 0;
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);
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