2016. 3. 2. 17:25
https://blog.naver.com/nagne2011/220643614050
class SaveText
{
private string saveData = "1.테스트\n 2.진행중\r\n 3.입니다.";
private string[] saveData2 = {"1.테스트\n", "2.진행중\r\n","3.입니다."}; //WriteAllLines전용 배열형식의 string
private const string path1 = "./save";
private const string path2 = ".\\save";
private const string path3 = @".\save"; //@가 붙은 string은 폴더 경로로 설정됨
//셋다 같은 의미
//파일 스트림 방식으로 저장하는 방법
public void SaveByFileStream(string fileName = "Save_FileStream.txt")
{
string fullPath = path1 + "/" + fileName;
//스트링 빌더, 를 사용해도 된다
try
{//만약을 위해
FileStream fs = new FileStream(
fullPath, //위치
FileMode.Create, //파일을 어떻게 열것인가?, createNew인 경우엔, 같은거 있을경우 exception으로 넘어감
FileAccess.Write); //파일 퍼미션 셋팅, 어떤 방식으로 열것인가?
byte[] bytes = Encoding.UTF8.GetBytes(saveData); //'saveDat'를 UTF8로 변환후 bytes로 넣어줌
fs.Write(bytes, 0, bytes.Length);
fs.Close();
}
catch(DirectoryNotFoundException e)
{
Console.WriteLine("디렉토리가 없습니다. 생성합니다.");
Directory.CreateDirectory(path1); //디렉토리 생성
SaveByFileStream(fileName);
}
catch(Exception e)
{
Console.WriteLine(e);
return;
}
Console.WriteLine("세이브가 완료되었습니다. FileStream");
}
//StreamWriter로 저장하는 방법
public void SaveByStreamWriter(string fileName ="Save_StreamWriter.txt")
{
string fullPath = path1 + "/" + fileName;
try
{
FileStream fs = new FileStream(
fullPath,
FileMode.Create,
FileAccess.Write);
StreamWriter sw = new StreamWriter(fs); //스트림 라이터로 만드는거라 새로 만들어줘야함
sw.WriteLine(saveData);
sw.Close();
fs.Close();
}
catch (DirectoryNotFoundException e)
{
Console.WriteLine("디렉토리가 없습니다. 생성합니다.");
Directory.CreateDirectory(path1); //디렉토리 생성
SaveByFileStream(fileName);
}
catch (Exception e)
{
Console.WriteLine(e);
return;
}
Console.WriteLine("세이브가 완료되었습니다. StreamWriter");
}
//SaveByWriteAllText방식으로 저장하는 방법
public void SaveByWriteAllText(string fileName = "Save_WriteAllText.txt")
{
string fullPath = path1 + "/" + fileName;
try
{
File.WriteAllText(fullPath, saveData);
}
catch (DirectoryNotFoundException e)
{
Console.WriteLine("디렉토리가 없습니다. 생성합니다.");
Directory.CreateDirectory(path1); //디렉토리 생성
SaveByFileStream(fileName);
}
catch (Exception e)
{
Console.WriteLine(e);
return;
}
Console.WriteLine("세이브가 완료되었습니다. SaveByWriteAllText");
}
//SaveByWriteAllLines방식으로 저장하는 방법
public void SaveByWriteAllLines(string fileName ="Save_WriteAllLines.txt")
{
string fullPath = path1 + "/" + fileName;
try
{
File.WriteAllLines(fullPath, saveData2);
}
catch (DirectoryNotFoundException e)
{
Console.WriteLine("디렉토리가 없습니다. 생성합니다.");
Directory.CreateDirectory(path1); //디렉토리 생성
SaveByFileStream(fileName);
}
catch (Exception e)
{
Console.WriteLine(e);
return;
}
Console.WriteLine("세이브가 완료되었습니다. WriteAllLines");
}
}
728x90
'개발공부' 카테고리의 다른 글
예외처리 try, catch, throw (0) | 2022.02.14 |
---|---|
c# XML 저장 불러오기 (0) | 2022.02.13 |
c# try-catch (0) | 2022.02.13 |
c# 함수 상속 (0) | 2022.02.13 |
c# 함수 기초 (0) | 2022.02.13 |