說明(2017-7-31 16:25:06):
1. 有兩種辦法,第一種是用FileStream創建txt,用StreamWriter寫入數據,期間還要加上判斷,是否存在這個txt文件,如果不存在就創建,存在就追加寫入。太麻煩了!
2. 第二種是直接File.AppendAllText(string path, string contents);第一個參數是txt路徑+文件名,第二個參數是寫入內容。這個方法會自己判斷文件是否存在,直接一步到位!
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Windows; namespace PPTtoJPG { public class MyLog { public void ShowLog(string log) { //第一種方法,太麻煩了 //StreamWriter sw = null; //if (!File.Exists("log.txt")) //{ // FileStream fs = new FileStream("log.txt", FileMode.Create, FileAccess.Write); // sw = new StreamWriter(fs); // sw.WriteLine(log); // //記得要關閉!不然里面沒有字! // sw.Close(); // fs.Close(); //} //else //{ // sw = File.AppendText("log.txt"); // sw.WriteLine(log); // sw.Close(); // //MessageBox.Show("已經有log文件了!"); //} //第二種方法,比較簡單 //\r\n要加在前面才會換行! File.AppendAllText("log.txt", "\r\n"+log); } } }