http://msdn.microsoft.com/ko-kr/library/8bh11f1k.aspx
[쓰기]
다음 코드 예제에서는 파일에 텍스트를 쓰는 여러 가지 방법을 보여 줍니다.System.IO.File class to write either a complete array of strings or a complete string to a text file.' xml:space="preserve">처음 두 예제에서는 System.IO.File 클래스의 정적 메서드를 사용하여 전체 문자열 배열 또는 전체 문자열을 텍스트 파일에 씁니다.세 번째 예제에서는 파일에 쓰기 전에 각 줄을 개별적으로 처리해야 경우 파일에 텍스트를 추가하는 방법을 보여 줍니다.이 세 예제 모두 파일의 모든 기존 내용을 덮어씁니다.네 번째 예제에서는 기존 파일에 텍스트를 덧붙이는 방법을 보여 줍니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | class WriteTextFile
{
static void Main()
{
string [] lines = { "First line" , "Second line" , "Third line" };
System.IO.File.WriteAllLines( @"C:\Users\Public\TestFolder\WriteLines.txt" , lines);
string text = "A class is the most powerful data type in C#. Like structures, " +
"a class defines the data and behavior of the data type. " ;
System.IO.File.WriteAllText( @"C:\Users\Public\TestFolder\WriteText.txt" , text);
using (System.IO.StreamWriter file = new System.IO.StreamWriter( @"C:\Users\Public\TestFolder\WriteLines2.txt" ))
{
foreach ( string line in lines)
{
if (!line.Contains( "Second" ))
{
file.WriteLine(line);
}
}
}
using (System.IO.StreamWriter file = new System.IO.StreamWriter( @"C:\Users\Public\TestFolder\WriteLines2.txt" , true ))
{
file.WriteLine( "Fourth line" );
}
}
}
|
[읽기]
정적 메서드를 사용 하 여이 예제 텍스트 파일의 내용을 읽어 ReadAllText 및 ReadAllLines 에서 System.IO.File 클래스입니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | class ReadFromFile
{
static void Main()
{
string text = System.IO.File.ReadAllText( @"C:\Users\Public\TestFolder\WriteText.txt" );
System.Console.WriteLine( "Contents of WriteText.txt = {0}" , text);
string [] lines = System.IO.File.ReadAllLines( @"C:\Users\Public\TestFolder\WriteLines2.txt" );
System.Console.WriteLine( "Contents of WriteLines2.txt = " );
foreach ( string line in lines)
{
Console.WriteLine( "\t" + line);
}
Console.WriteLine( "Press any key to exit." );
System.Console.ReadKey();
}
}
|