본문 바로가기
프로그래밍/C#.net

[C#] ASCII로 파일입출력 하기 예제

by 건우아빠유리남편 2009. 1. 15.
반응형

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ASCIIFileWriter
{
    class Program
    {
        //받을 버퍼의 크기
        const int ReadBufferSize = 128;

        static void Main(string[] args)
        {
            try
            {
                FileStream file = null;

                //읽기로 파일 열거나 생성
                file = new FileStream("ASCIIFileSample.txt",
                    FileMode.OpenOrCreate, FileAccess.Read);

                //버퍼 크기만큼 읽음
                byte[] buffer = new byte[ReadBufferSize];
                int readSize = file.Read(buffer, 0, ReadBufferSize);

                //읽은게 끝이 아니믄 계속 읽어
                while (readSize > 0)
                {
                    Console.Write(Encoding.ASCII.GetString(buffer,0,readSize));
                    readSize = file.Read(buffer, 0, ReadBufferSize);
                }
                file.Close();


                //쓰기 권한을 가진 ASCIIFileSample.txt생성
                file = new FileStream("ASCIIFileSample.txt",
                    FileMode.Append, FileAccess.Write);

                //"exit"라는 문자열이 나올 때까지 한줄씩 읽는다
                string inputString = Encoding.ASCII.GetString(buffer);
                inputString = Console.ReadLine();
                while (inputString.ToLower() != "exit")
                {
                    inputString += "\r\n";
                    file.Write(Encoding.ASCII.GetBytes(inputString), 0, inputString.Length);                   
                    inputString = Console.ReadLine();
                }

                file.Flush();
                file.Close();

            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }

        }
    }
}

반응형

'프로그래밍 > C#.net' 카테고리의 다른 글

WinService구동시 installutil문제  (2) 2009.02.17
[C#] AutoResetEvent 와 ManualResetEvnet 예제  (0) 2009.01.15
동기화 테스트 예제  (0) 2009.01.15
Thread 5분연습 예제  (0) 2009.01.15
[C#]String 클래스 사용법 예제  (0) 2009.01.15

댓글