반응형
txt 파일 쓰기, 읽기
// 파일에 쓸 텍스트
string textToWrite = "저장할 텍스트";
// 파일 경로
string filePath = "C:/Test/config.txt";
// 파일 쓰기
File.WriteAllText(filePath, textToWrite);
// 파일 읽기
string readText = File.ReadAllText(filePath);
json 파일 쓰기, 읽기(string)
- Newtonsoft.Json 라이브러리 사용
- C# 라이브러리 설치
C# 라이브러리 설치(NuGet 패키지 관리자)
NuGet 패키지 관리자를 사용한 설치 Visual Studio에서 NuGet 패키지 관리자 사용 Visual Studio를 열고, 솔루션 탐색기에서 프로젝트를 마우스 오른쪽 버튼으로 클릭 "NuGet 패키지 관리..."를 선택 패키지
lightgg.tistory.com
using Newtonsoft.Json;
// 파일에 쓸 텍스트
string textToWrite = "json 형식 입니다";
// 파일 경로
string filePath = "C:/Test/config.json";
// textToWrite 내용을 json 형식으로 변환
string jsonToWrite = JsonConvert.SerializeObject(textToWrite);
// 파일 쓰기
File.WriteAllText(filePath, jsonToWrite);
// 파일 읽기
string readJson = File.ReadAllText(filePath);
// json 형식 textToWrite 쓴 내용으로 읽기
var readText = JsonConvert.DeserializeObject<string>(readJson);
// 확인
Console.WriteLine(readText);
json 파일 쓰기, 읽기(class)
- Newtonsoft.Json 라이브러리 사용
using Newtonsoft.Json;
public class Person
{
public int age;
public string name;
}
Person p = new Person() { age = 7, name = "힐링" };
// 파일 경로
string filePath = "C:/Test/config.json";
// textToWrite 내용을 json 형식으로 변환
string jsonToWrite = JsonConvert.SerializeObject(p);
// 파일 쓰기
File.WriteAllText(filePath, jsonToWrite);
// 파일 읽기
string readJson = File.ReadAllText(filePath);
// json 형식 textToWrite 쓴 내용으로 읽기
var readText = JsonConvert.DeserializeObject<Person>(readJson);
// 확인
Console.WriteLine($"age: {readText.age}, name: {readText.name}");
반응형
'C#' 카테고리의 다른 글
C# 초기화 파일 생성 및 불러오기(json) (0) | 2024.01.08 |
---|---|
C# 간편한 로그 라이브러리(Serilog) (0) | 2024.01.07 |
C# 라이브러리 설치(NuGet 패키지 관리자) (0) | 2024.01.07 |
C# 경로에 파일이 있는지 확인(File.Exists) (0) | 2024.01.07 |
C# 소수점 두 자리 또는 세 자리 표시(ToString) (0) | 2024.01.07 |