C#

[C#]텍스트 파일 쓰기

DevStory 2022. 5. 1.

C# 파일에 텍스트 쓰기

System.IO 네임스페이스는 파일에서 데이터 생성, 수정 및 검색과 같은 다양한 작업을 수행하기 위한 클래스를 제공합니다. 이번 포스팅에서는 파일에 텍스트를 쓰기 위한 몇 가지 방법들을 소개합니다.


File 클래스

File 클래스는 파일에 텍스트를 쓰는 몇 가지 정적 메서드를 제공합니다. 사용 방법은 아래와 같으며 아래 예제는 파일이 존재하는지 체크하지 않습니다. 에러 또는 예외가 발생하는 경우 경로 및 폴더 존재 유무를 확인해주시길 바랍니다.


File.WriteAllText()

File.WriteAllText() 메서드는 새 파일을 생성하고 내용을 작성한 다음 파일을 닫습니다. 파일이 이미 존재하는 경우 내용을 덮어씁니다.

class Program
{
  static void Main(string[] args)
  {
    string path = @"C:\FileTest\FileTest.txt";
    string text = @"Some Text123123";

    File.WriteAllText(path, text);
  }
}

File.WriteAllLines()

File.WriteAllLines() 메서드는 새 파일을 생성하고 문자열 배열을 파일에 작성한 다음 파일을 닫습니다. 파일이 이미 존재하는 경우 내용을 덮어씁니다.

 

문자열 배열의 값은 라인으로 구분됩니다.

class Program
{
  static void Main(string[] args)
  {
    string path = @"C:\FileTest\FileTest.txt";
    string multiLineText = @"string1|string2|string3";

    File.WriteAllLines(path, multiLineText.Split("|"));
  }
}

실행 결과


File.WriteAllBytes()

File.WriteAllBytes() 메서드는 새 파일을 생성하고 바이트 배열을 파일에 작성한 다음 파일을 닫습니다. 파일이 이미 존재하는 경우 내용을 덮어씁니다.

class Program
{
  static void Main(string[] args)
  {
    string path = @"C:\FileTest\FileTest.txt";
    string text = @"File Write";

    byte[] bytes = Encoding.ASCII.GetBytes(text);
    File.WriteAllBytes(path, bytes);
  }
}

위에서 설명한 WriteAllText(), WriteAllLines(), WriteAllBytes() 메서드는 기존 파일의 내용을 덮어씁니다. 파일에 내용을 추가하고 싶은 경우 AppendText(), AppendAllText(), AppendAllLines() 메서드를 사용합니다.

반응형

StreamWriter 클래스

StreamWriter 클래스는 파일에 데이터를 쓰기 위한 다양한 방법을 제공하는 클래스입니다. 스트림에 문자열을 쓰기 위해 Write() 메서드를 사용할 수 있으며, 라인을 추가하는 경우 WriteLine() 메서드를 사용합니다.

class Program
{
  static void Main(string[] args)
  {
    string path = @"C:\FileTest\FileTest.txt";
    FileStream fs = new FileStream(path, FileMode.OpenOrCreate);

    StreamWriter sw = new StreamWriter(fs);

    sw.WriteLine("Hello");
    sw.WriteLine("World");

    sw.Write("Hello");
    sw.Write("World");

    sw.Close();
    fs.Close();
  }
}

실행 결과

FileStream 객체를 초기화 후 StreamWirter 생성자에 FileStream 객체를 전달합니다. WrteLine() 메서드와 Write() 메서드를 사용하여 파일에 텍스트를 추가합니다.

 

WriteLine() 메서드를 사용하는 경우 라인이 추가된 것을 확인할 수 있으며, StreamWriter 객체를 close() 후 FileStream 객체도 close() 합니다.


FileStream 클래스

FileStream 클래스는 파일에 텍스트를 쓰기 위한 여러 메서드를 제공합니다. 단일 바이트를 쓰는 경우 WriteByte() 메서드를 사용할 수 있으며, 바이트 배열을 쓰는 경우 Write() 메서드를 사용합니다.

class Program
{
  static void Main(string[] args)
  {
    string path = @"C:\FileTest\FileTest.txt"; 
    FileStream fs = new FileStream(path, FileMode.OpenOrCreate);

    string text = "Hello\n";
    byte[] bytes = Encoding.ASCII.GetBytes(text);
    fs.Write(bytes, 0, bytes.Length);

    fs.WriteByte(70);

    fs.Close();
  }
}

실행 결과

String 변수를 바이트 배열로 변환 후 Write() 메서드를 사용하여 데이터를 작성했습니다. 바이트 배열이 아닌 단일 바이트를 쓰는 경우 WriteByte() 메서드를 사용합니다.

반응형

'C#' 카테고리의 다른 글

[C#]소멸자(destructor)  (0) 2022.05.02
[C#]DataTable을 List로 변환  (0) 2022.05.01
[C#]람다식, 람다표현식(Lambda expression)  (0) 2022.05.01
[C#]SortedList 클래스  (0) 2022.02.06
[C#]yield 키워드  (0) 2022.02.06

댓글