C# 將文本寫入到文件


將字符串數組寫入到文件,每個元素為一行

string[] lines = { "First line", "Second line", "Third line" };

System.IO.File.WriteAllLines( @"C:\Users\Public\TsetFolder\WriteLines.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:\Users\Public\TestFolder\WriteText.txt", text);

 

使用using語句動態寫入到文件

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" );

}    

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM