C# json settings read and write example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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