将字符串数组写入到文件,每个元素为一行
string[] lines = { "First line", "Second line", "Third line" };
System.IO.File.WriteAllLines( @"C:UsersPublicTsetFolderWriteLines.txt", lines );
将字符串写入到文件
string text = "A class is the most powerful data type in C#. Like a structure, " + "a class defines the data and behavior of the data type. ";
System.IO.File.WriteAllText(@"C:UsersPublicTestFolderWriteText.txt", text);
使用using语句动态写入到文件
using( System.IO.StreamWriter file = new System.IO.StreamWriter( @"C:UsersPublicTestFolderWriteLines2.txt" ) ){
foreach( string line in lines ){
if ( !line,Contains("Second") ){
file.WriteLine(line);
}
}
}
将文本追加到文件末尾
using( System.IO.StreamWriter file = new System.IO.StreamWriter( @"C:UsersPublicTestFolderWriteLines2.txt", true ) ){
file.WriteLine( "Fourth line" );
}