C#學習筆記(22)——C#建立文字檔txt並追加寫入資料

來源:互聯網
上載者:User

標籤:writer   mode   contents   append   new   class   message   檔案名稱   pen   

說明(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);        }    }}

 

C#學習筆記(22)——C#建立文字檔txt並追加寫入資料

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.