파일 로드 - FileStream, StreamReader, ReadAllText, ReadAllLines
//파일 로드 - FileStream, StreamReader, ReadAllText, ReadAllLines
//이전 글 - 파일 저장과 대입되는 4가지 방법 이다.
private string loadData; //로드한 데이터를 담을 변수
//디렉터리 경로 지정
private const string path = "./save/test1/"; //요즘 많이 사용하는 방법 /
private const string path2 = ".\\save\\test2"; //옛날부터 디렉터리 구분하는 방법 \\
private const string path3 = @".\save\test3"; //@뒤에 있는 string은 디렉터리를 표시하는 것이라고 지정 - 최신
private void PrintLoadData()
{
Console.WriteLine("읽은 데이터는 다음과 같습니다.");
Console.WriteLine("{0}\n", loadData);
}
//로드
//1. FileStream
public void LoadFromFileStream(string fileName = "S_FileString.txt")
{
string fullpath = path + "/" + fileName; //그냥 쉽게 하려고 쓴것이다. 성능은 StringBuilder이 좋다.
try
{
//파일 스트림 생성. cs파일 상단에 using System.IO; 추가
FileStream fs = new FileStream(
fullpath,
FileMode.Open,
FileAccess.Read);
//바이트 단위로 로드
byte[] bytes = new byte[fs.Length];
fs.Read(bytes, 0, bytes.Length);
loadData = Encoding.UTF8.GetString(bytes);
fs.Close();
}
//파일 못찾음
catch (FileNotFoundException) //변수 없어도 됨
{
Console.WriteLine("파일을 찾지 못했습니다.");
return;
}
//디렉터리 못찾음
catch(DirectoryNotFoundException)
{
Console.WriteLine("폴더가 없습니다.");
return;
}
catch (Exception e)
{
Console.WriteLine(e);
}
Console.WriteLine("로딩 완료 LoadFromFileStream");
PrintLoadData();
}
//2. StreamReader
public void LoadFromStreamReader(string fileName = "S_StreamWriter.txt")
{
string fullpath = path2 + "/" + fileName;
try
{
FileStream fs = new FileStream(
fullpath,
FileMode.Open,
FileAccess.Read);
StreamReader sr = new StreamReader(fs); //스트림 생성
string line;
StringBuilder builder = new StringBuilder();
while((line = sr.ReadLine()) != null) //한줄 읽는데 null이 아니면
{
builder.Append(line); //한줄 저장
builder.Append("\n"); //개행
}
loadData = builder.ToString();
sr.Close();
fs.Close();
}
//파일 못찾음
catch (FileNotFoundException) //변수 없어도 됨
{
Console.WriteLine("파일을 찾지 못했습니다.");
return;
}
//디렉터리 못찾음
catch (DirectoryNotFoundException)
{
Console.WriteLine("폴더가 없습니다.");
return;
}
catch (Exception e)
{
Console.WriteLine(e);
}
Console.WriteLine("로딩 완료 LoadFromStreamReader");
PrintLoadData();
}
//3. ReadAllText
public void LoadFromReadAllText(string fileName = "S_WriteAllText.txt")
{
string fullpath = path3 + "/" + fileName;
try
{
loadData = File.ReadAllText(fullpath); //걍 모두 저장. 한줄이라 참쉽다.
}
//파일 못찾음
catch (FileNotFoundException) //변수 없어도 됨
{
Console.WriteLine("파일을 찾지 못했습니다.");
return;
}
//디렉터리 못찾음
catch (DirectoryNotFoundException)
{
Console.WriteLine("폴더가 없습니다.");
return;
}
catch (Exception e)
{
Console.WriteLine(e);
}
Console.WriteLine("로딩 완료 LoadFromReadAllText");
PrintLoadData();
}
//4. ReadAllLines
public void LoadFromReadAllLines(string fileName = "S_WriteAllLines.txt")
{
string fullpath = path2 + "/" + fileName;
try
{
string[] lines = File.ReadAllLines(fullpath); //라인별로 string 배열에 저장
StringBuilder builder = new StringBuilder(lines.Length); //스트링 변수의 크기를 알고 있으면 선언해주는게 좋다
foreach(var line in lines)
{
builder.Append(line);
builder.Append("\n");
}
loadData = builder.ToString();
}
//파일 못찾음
catch (FileNotFoundException) //변수 없어도 됨
{
Console.WriteLine("파일을 찾지 못했습니다.");
return;
}
//디렉터리 못찾음
catch (DirectoryNotFoundException)
{
Console.WriteLine("폴더가 없습니다.");
return;
}
catch (Exception e)
{
Console.WriteLine(e);
}
Console.WriteLine("로딩 완료 LoadFromReadAllLines");
PrintLoadData();
}
'공부 > C#' 카테고리의 다른 글
Console 키입력 - Console.ReadKey, ConsoleKeyInfo (0) | 2016.05.12 |
---|---|
예외처리 - try, catch, finally, throw new Exception (0) | 2016.05.12 |
파일 저장 - FileStream, StreamWriter, WriteAllText, WriteAllLines (0) | 2016.05.12 |
컬렉션(Collection), 제네릭 컬렉션(Generic Collection) - 예) ArrayList, List<T> (0) | 2016.05.11 |
C#에서의 struct(구조체)와 class - 메모리 구조 차이, Boxing, Unboxing 예제소스 (0) | 2016.05.11 |