c# 강의/과제
20200421 - File 읽기 (JSON)
쪼혀
2020. 4. 22. 01:15
> File.ReadAllText() -- 모든 문자열 읽기
더보기
public void ReadAllTextTest()
{
string path = "./cookie_data.json";
string json = File.ReadAllText(path);
Console.WriteLine(json);
CookieData[] arrCookieDatas = JsonConvert.DeserializeObject<CookieData[]>(json);
foreach (var item in arrCookieDatas)
{
Console.WriteLine($"{item.id} / {item.name} / {item.grade}");
}
}
> File.ReadAllLines() -- 문자열 한줄씩 읽어오기
더보기
public void ReadAllLinesTest()
{
string path = "./cookie_data.json";
string[] textValue = File.ReadAllLines(path);
string fullTextValue = "";
foreach (var item in textValue)
{
fullTextValue += item;
}
Console.WriteLine(fullTextValue);
CookieData[] arrCookieDatas = JsonConvert.DeserializeObject<CookieData[]>(fullTextValue);
foreach (var item in arrCookieDatas)
{
Console.WriteLine($"{item.id} / {item.name} / {item.grade}");
}
}
> File.OpenRead() / new StreamReader() -- 파일 읽어와 textReader 스트림에서 문자열 읽기
더보기
public void FileStreamTest()
{
string path = "./cookie_data.json";
FileStream fs = File.OpenRead(path);
StreamReader sr = new StreamReader(fs);
// sr.ReadToEnd() 스트림 끝까지 모든 문자를 읽기
CookieData[] arrCookieDatas = JsonConvert.DeserializeObject<CookieData[]>(sr.ReadToEnd());
foreach (var item in arrCookieDatas)
{
Console.WriteLine($"{item.id} / {item.name} / {item.grade}");
}
}
> File.ReadAllLines()
더보기
string[] jsonLines = File.ReadAllLines(fileDir);
> CookieData.cs
더보기
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _20200421_json
{
class CookieData
{
public int id;
public string name;
public int grade;
}
}