공부/C#

파일 저장 - FileStream, StreamWriter, WriteAllText, WriteAllLines

미다손 2016. 5. 12. 04:50

//파일 저장 - FileStream, StreamWriter, WriteAllText, WriteAllLines

//4가지 방법

//string 1줄

        private string saveData = "1.테스트\n2.진행중\r\n3.입니다.";

//\n 개행 \r 캐리지리턴 - 시스템마다 개행을 나타내는 문자가 달라서 적음 \r


//string배열

        private string[] saveData2 = { "1.테스트", "2.진행중", "3.입니다." };


//디렉터리(폴더) 경로 지정

        private const string path = "./save/test1/";   //요즘 많이 사용하는 방법 /

        private const string path2 = ".\\save\\test2"; //옛날부터 디렉터리 구분하는 방법 \\

        private const string path3 = @".\save\test3"; //@뒤에 있는 string은 디렉터리를 표시하는 것이라고 지정 - 최신


//1.FileStream

        public void SaveByFileStream(string fileName = "S_FileString.txt")

        {

            StringBuilder fullPath = new StringBuilder();

            fullPath.Append(path);

            fullPath.Append("/");

            fullPath.Append(fileName);

            //string fullPath = path + "/" + fileName;


            try

            {

            //상단에 using System.IO; 추가

            FileStream fs = new FileStream(

                fullPath.ToString(), 

                FileMode.Create, 

                FileAccess.Write);

            //Byte단위로 바꾸어 주어야 함.


            byte[] bytes = Encoding.UTF8.GetBytes(saveData);    //string문자가 UTF8인코딩으로 byte화

            fs.Write(bytes, 0, bytes.Length);    //byte 저장. 0부터 총 길이만큼

            fs.Close();


            }

            catch(DirectoryNotFoundException e)

            {

                Console.WriteLine("디렉터리가 없습니다. 생성합니다.");

                Directory.CreateDirectory(path);

                SaveByFileStream(fileName);

                return;

            }

            catch(Exception e)

            {

                Console.WriteLine(e);

                return;

            }

            Console.WriteLine("세이브 완료(SaveByFileStream)");

        }


        //2.StreamWriter

        public void SaveByFileStreamWriter(string fileName = "S_StreamWriter.txt")

        {

            StringBuilder fullPath = new StringBuilder();

            fullPath.Append(path2);

            fullPath.Append("/");

            fullPath.Append(fileName);

        


            try

            {

                //상단에 using System.IO; 추가

                FileStream fs = new FileStream(

                    fullPath.ToString(),

                    FileMode.Create,

                    FileAccess.Write);

                StreamWriter sw = new StreamWriter(fs);    //스트림을 만들어서 

                sw.WriteLine(saveData);    //일괄 저장

                sw.Close();

                fs.Close();


            }

            catch (DirectoryNotFoundException e)

            {

                Console.WriteLine("디렉터리가 없습니다. 생성합니다.");

                Directory.CreateDirectory(path2);    //디렉터리 생성

                SaveByFileStreamWriter(fileName);   //자기 자신 다시 부름

                return; //함수 종료

            }

            catch (Exception e)

            {

                Console.WriteLine(e);

                return;

            }

            Console.WriteLine("세이브 완료(SaveByFileStreamWriter)");

        }



        //3.WriteAllText

        public void SaveByWriteAllText(string fileName = "S_WriteAllText.txt")

        {

            StringBuilder fullPath = new StringBuilder();

            fullPath.Append(path3);

            fullPath.Append("/");

            fullPath.Append(fileName);

            //string fullPath = path + "/" + fileName;


            try

            {

                File.WriteAllText(fullPath.ToString(), saveData);  //핵심 - string 통째로 저장

            }

            catch (DirectoryNotFoundException e)

            {

                Console.WriteLine("디렉터리가 없습니다. 생성합니다.");

                Directory.CreateDirectory(path3);    //디렉터리 생성

                SaveByWriteAllText(fileName);   //자기 자신 다시 부름

                return; //함수 종료

            }

            catch (Exception e)

            {

                Console.WriteLine(e);

                return;

            }

            Console.WriteLine("세이브 완료(SaveByWriteAllText)");

        }


        //4.WriteAllLines

        public void SaveByWriteAllLines(string fileName = "S_WriteAllLines.txt")

        {

            StringBuilder fullPath = new StringBuilder();

            fullPath.Append(path2);

            fullPath.Append("/");

            fullPath.Append(fileName);

            //string fullPath = path + "/" + fileName;


            try

            {

                File.WriteAllLines(fullPath.ToString(), saveData2);    //핵심 - string 배열 저장

            }

            catch (DirectoryNotFoundException e)

            {

                Console.WriteLine("디렉터리가 없습니다. 생성합니다.");

                Directory.CreateDirectory(path2);    //디렉터리 생성

                SaveByWriteAllLines(fileName);   //자기 자신 다시 부름

                return; //함수 종료

            }

            catch (Exception e)

            {

                Console.WriteLine(e);

                return;

            }

            Console.WriteLine("세이브 완료(SaveByWriteAllLines)");

        }

//짧은게 쓰기에는 편하지만 준비과정이 길고 쓰기 불편하게 성능은 더 좋지 않을 까 한다.