.NET에서 텍스트 파일의 내용을 문자열로 읽는 가장 좋은 방법은 무엇입니까?

StackOverflow https://stackoverflow.com/questions/42286

  •  09-06-2019
  •  | 
  •  

문제

이보다 더 짧은 내용이 있어야 할 것 같습니다.

private string LoadFromFile(string path)
{
   try
   {
       string fileContents;
       using(StreamReader rdr = File.OpenText(path))
       {
            fileContents = rdr.ReadToEnd();
       }

       return fileContents;
   }
   catch
   {
       throw;
   }
}
도움이 되었습니까?

해결책

우선, 제목은 "strnig의 내용을 텍스트 파일에 쓰는 방법"을 요청하지만 코드 예제는 "텍스트 파일의 내용을 문자열로 읽는 방법에 대한 것입니다.

두 질문에 대한 답변:

using System.IO;
...
string filename = "C:/example.txt";
string content = File.ReadAllText(filename);
File.WriteAllText(filename, content);

문자열 대신 문자열 배열이나 바이트 배열을 원하는 경우 ReadAllLines/WriteAllLines 및 ReadAllBytes/WriteAllBytes도 참조하세요.

다른 팁

string text = File.ReadAllText("c:\file1.txt");
File.WriteAllText("c:\file2.txt", text);

ReadAllLines/WriteAllLines 및 ReadAllBytes/WriteAllBytes도 확인하세요.

해당 예외 처리기에는 의미가 없습니다.아무것도 하지 않습니다.이것은 코드의 단축 버전이므로 괜찮습니다.

 private string LoadFromFile(string path)
 {
    using(StreamReader rdr = File.OpenText(path))
      return rdr.ReadToEnd();
 }

File.ReadAllText() 아마도요?

VS2008의 도움말이 설치된 경우 ms-help://MS.VSCC.v90/MS.MSDNQTR.v90.en/fxref_mscorlib/html/4803f846-3d8a-de8a-18eb-32cfcd038f76.htm.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top