본문 바로가기

C#

C# 초기화 파일 생성 및 불러오기(json)

반응형

초기화 파일 생성 및 불러오기

  • 해당 코드는 윈폼(Windows Forms)에서 작성함
  • cs 파일은 Data.cs, Enum.cs, JsonHelper.cs 파일을 추가
  • 필요한 NuGet 패키지
    • Serilog.AspNetCore
    • Newtonsoft.Json
  • Serilog 라이브러리 설치 및 사용법
 

C# 간편한 로그 라이브러리(Serilog)

간편한 로그 Serilog Serilog.AspNetCore 라이브러리 사용 Serilog, Serilog.Sinks.FIle, Serilog.Sinks.Console 각각 설치해야하는데 한 번에 설치를 위해 blazor 웹 개발에서도 사용 가능 C# 라이브러리 설치 방법 C# 라

lightgg.tistory.com

 

//Program.cs

using System.Runtime.InteropServices;
using Serilog;

namespace ExcelToJson
{
    internal static class Program
    {
        [DllImport("kernel32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool AllocConsole();

        [STAThread]
        static void Main()
        {
            AllocConsole(); // 콘솔 창 할당

            // Serilog 초기화
            Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Debug()
                .WriteTo.Console()
                .WriteTo.File($"logs/log_.txt", rollingInterval: RollingInterval.Day)
                .CreateLogger();

            ApplicationConfiguration.Initialize();
            Application.Run(new Form1());
        }
    }
}

 

//Form1.cs

using Serilog; // Log.Information, Log.Error 메서드 사용시 필요

public partial class Form1 : Form
{
	string filePath = "config.json";

	public Form1()
	{
		InitializeComponent();

		var tuple = JsonHelper.JsonFileRead<Config>(filePath);
		if (tuple.Item1 != ErrorCode.Ok)
		{
			ErrorCode error = tuple.Item1;
			Log.Error($"ExcelToJson_Click, JsonHelper.JsonFileWrite, error: {error}");
			return;
		}
		var config = tuple.Item2;

		textBox1.Text = config.CommonExcel;
		textBox2.Text = config.ServerExcel;
		textBox3.Text = config.ClientJson;
		textBox4.Text = config.ServerJson;

		Log.Information($"초기화 성공");
	}

	private void ExcelToJson_Click(object sender, EventArgs e)
	{
		Config config = new Config()
		{
			CommonExcel = textBox1.Text,
			ServerExcel = textBox2.Text,
			ClientJson = textBox3.Text,
			ServerJson = textBox4.Text,
		};

		var error = JsonHelper.JsonFileWrite(config, filePath);
		if (error != ErrorCode.Ok)
		{
			Log.Error($"ExcelToJson_Click, JsonHelper.JsonFileWrite, error: {error}");
			return;
		}
	}
}

 

//Data.cs

public class Config
{
    public string? CommonExcel; // 입력 위치에서 엑셀들을 읽어들여 ClientJson & ServerJson 위치에 생성
    public string? ServerExcel; // 입력 위치에서 엑셀들을 읽어들여 ServerJson 위치에 생성
    public string? ClientJson; // 입력 위치에 json 파일 생성
    public string? ServerJson; // 입력 위치에 json 파일 생성
}

 

//Enum.cs

public enum ErrorCode
{ 
    Ok = 0,
    IsNullOrEmpty = 1,
    FileExistsNot = 2,
}

 

//JsonHelper.cs

using Serilog;
using Newtonsoft.Json;

public static class JsonHelper
{
    public static ErrorCode JsonFileWrite<T>(T obj, string filePath)
    {
        ErrorCode error = ErrorCode.Ok;

        // 파일 경로가 유효한지 확인
        if (string.IsNullOrWhiteSpace(filePath))
        {
            error = ErrorCode.IsNullOrEmpty;
            Log.Error($"JsonFileWrite, string.IsNullOrEmpty, filePath: {filePath}");
            return error;
        }

        // 객체를 JSON으로 변환
        string jsonString = JsonConvert.SerializeObject(obj, Formatting.Indented);

        // 파일 쓰기
        File.WriteAllText(filePath, jsonString);

        return error;
    }

    public static (ErrorCode, T?) JsonFileRead<T>(string filePath)
    {
        ErrorCode error = ErrorCode.Ok;
        var ack = default(T);

        // 파일 경로가 유효한지 확인
        if (string.IsNullOrWhiteSpace(filePath))
        {
            error = ErrorCode.IsNullOrEmpty;
            Log.Error($"JsonFileRead, string.IsNullOrEmpty, filePath: {filePath}");
            return (error, ack);
        }

        if (File.Exists(filePath) == false)
        {
            error = ErrorCode.FileExistsNot;
            Log.Error($"JsonFileRead, File.Exists, filePath: {filePath}");
            return (error, ack);
        }

        // 파일에서 JSON 읽기
        string jsonString = File.ReadAllText(filePath);

        // 객체를 JSON으로 변환
        ack = JsonConvert.DeserializeObject<T>(jsonString);

        return (error, ack);
    }
}

 

처음 실행 화면

 

각 TextBox에 입력 후 Excel To Json 버튼 실행

 

Excel To Json 버튼 실행시 생성되는 config.json 파일 화면

 

프로그램을 닫고 재실행시 config.json을 읽어들여 윈포에서 보여지는 화면

반응형