logo

C#에서 텍스트 파일을 읽고 쓰는 방법은 무엇입니까?

프로그램이 종료되면 해당 프로그램과 관련된 모든 데이터가 삭제됩니다. 따라서 데이터를 어딘가에 저장해야 합니다. 파일은 데이터를 영구적으로 저장하고 공유하는 데 사용됩니다. C#을 사용하면 텍스트 파일에 저장된 데이터를 검색하고 조작할 수 있습니다.

Java를 배열로 나열

텍스트 파일 읽기: C#의 파일 클래스는 텍스트 파일을 읽는 두 가지 정적 메서드를 정의합니다. 파일.읽기모든텍스트() 그리고 파일.ReadAllLines() .



  • File.ReadAllText()는 전체 파일을 한 번에 읽고 문자열을 반환합니다. 이 문자열을 변수에 저장하고 이를 사용하여 화면에 내용을 표시해야 합니다.
  • File.ReadAllLines()는 파일을 한 번에 한 줄씩 읽고 해당 줄을 문자열 형식으로 반환합니다. 각 줄을 저장하려면 문자열 배열이 필요합니다. 동일한 문자열 배열을 사용하여 파일의 내용을 표시합니다.

파일을 읽는 또 다른 방법은 StreamReader 개체를 사용하는 것입니다. StreamReader는 또한 한 번에 한 줄을 읽고 문자열을 반환합니다. 위에서 언급한 파일을 읽는 모든 방법은 아래 제공된 예제 코드에 설명되어 있습니다.








// C# program to illustrate how> // to read a file in C#> using> System;> using> System.IO;> > class> Program {> >static> void> Main(>string>[] args)> >{> >// Store the path of the textfile in your system> >string> file =>@'M:DocumentsTextfile.txt'>;> > >Console.WriteLine(>'Reading File using File.ReadAllText()'>);> > >// To read the entire file at once> >if> (File.Exists(file)) {> >// Read all the content in one string> >// and display the string> >string> str = File.ReadAllText(file);> >Console.WriteLine(str);> >}> >Console.WriteLine();> > >Console.WriteLine(>'Reading File using File.ReadAllLines()'>);> > >// To read a text file line by line> >if> (File.Exists(file)) {> >// Store each line in array of strings> >string>[] lines = File.ReadAllLines(file);> > >foreach>(>string> ln>in> lines)> >Console.WriteLine(ln);> >}> >Console.WriteLine();> > >Console.WriteLine(>'Reading File using StreamReader'>);> > >// By using StreamReader> >if> (File.Exists(file)) {> >// Reads file line by line> >StreamReader Textfile =>new> StreamReader(file);> >string> line;> > >while> ((line = Textfile.ReadLine()) !=>null>) {> >Console.WriteLine(line);> >}> > >Textfile.Close();> > >Console.ReadKey();> >}> >Console.WriteLine();> >}> }>

>

자바의 jvm

>

이 프로그램을 실행하려면 다음과 같이 파일을 저장하십시오. .cs 확장을 사용하여 실행할 수 있습니다. csc 파일 이름.cs cmd에서 명령을 실행하세요. 또는 Visual Studio . 여기에는 다음과 같은 이름의 텍스트 파일이 있습니다. 텍스트파일.txt 출력에 콘텐츠가 표시됩니다.

산출:

C#에서 텍스트 파일 읽기

텍스트 파일 작성: C#의 File 클래스는 텍스트 파일을 작성하는 두 가지 정적 메서드를 정의합니다. 파일.WriteAllText() 그리고 파일.쓰기모든라인() .

  • File.WriteAllText()는 전체 파일을 한 번에 씁니다. 파일 경로와 작성해야 하는 텍스트라는 두 가지 인수를 사용합니다.
  • File.WriteAllLines()는 한 번에 한 줄씩 파일을 씁니다. 파일 경로와 작성해야 하는 텍스트(문자열 배열)라는 두 개의 인수를 사용합니다.

파일에 쓰는 또 다른 방법은 StreamWriter 개체를 사용하는 것입니다. StreamWriter는 한 번에 한 줄씩 씁니다. 세 가지 쓰기 방법 모두 파일이 없으면 새 파일을 생성하지만 해당 파일이 지정된 위치에 이미 있으면 덮어씁니다. 위에서 언급한 텍스트 파일에 쓰는 모든 방법은 아래 제공된 예제 코드에 설명되어 있습니다.


char를 int로 자바



// C# program to illustrate how> // to write a file in C#> using> System;> using> System.IO;> > class> Program {> >static> void> Main(>string>[] args)> >{> >// Store the path of the textfile in your system> >string> file =>@'M:DocumentsTextfile.txt'>;> > >// To write all of the text to the file> >string> text =>'This is some text.'>;> >File.WriteAllText(file, text);> > >// To display current contents of the file> >Console.WriteLine(File.ReadAllText(file));> >Console.WriteLine();> > >// To write text to file line by line> >string>[] textLines1 = {>'This is the first line'>,> >'This is the second line'>,> >'This is the third line'> };> > >File.WriteAllLines(file, textLines1);> > >// To display current contents of the file> >Console.WriteLine(File.ReadAllText(file));> > >// To write to a file using StreamWriter> >// Writes line by line> >string>[] textLines2 = {>'This is the new first line'>,> >'This is the new second line'> };> > >using>(StreamWriter writer =>new> StreamWriter(file))> >{> >foreach>(>string> ln>in> textLines2)> >{> >writer.WriteLine(ln);> >}> >}> >// To display current contents of the file> >Console.WriteLine(File.ReadAllText(file));> > >Console.ReadKey();> >}> }>

>

문자열을 날짜로 변환
>

이 프로그램을 실행하려면 다음과 같이 파일을 저장하십시오. .cs 확장을 사용하여 실행할 수 있습니다. csc 파일 이름.cs cmd에서 명령을 실행하세요. 또는 Visual Studio .

산출:

C#으로 파일 쓰기

이미 저장된 데이터를 덮어쓰지 않고 기존 파일에 더 많은 텍스트를 추가하려는 경우 System.IO의 File 클래스에서 제공하는 추가 메서드를 사용할 수 있습니다.


json 형식의 예



using> System;> using> System.IO;> > class> Program {> >static> void> Main(>string>[] args)> >{> >// Store the path of the textfile in your system> >string> file =>@'M:DocumentsTextfile.txt'>;> > >// To write all of the text to the file> >string> text1 =>'This is some text.'>;> >File.WriteAllText(file, text1);> > >// To append text to a file> >string> text2 =>'This is text to be appended'>;> >File.AppendAllText(file, text2);> > >// To display current contents of the file> >Console.WriteLine(File.ReadAllText(file));> >Console.ReadKey();> >}> }>

>

>

산출:

C#에서 파일에 텍스트 추가