asp.net c寫檔案函數執行個體代碼

來源:互聯網
上載者:User

asp教程.net c寫檔案函數執行個體代碼
streamwriter 和 streamreader 向流寫入字元並從流讀取字元。下面的程式碼範例開啟 log.txt 檔案(如果檔案不存在則建立檔案)以進行輸入,並將資訊附加到檔案尾。然後將檔案的內容寫入標準輸出,以便顯示出來。

[c#]
using system;
using system.io;
class dirappend
{
  public static void main(string[] args)
  {
  streamwriter w = file.appendtext("log.txt");
  log ("test1", w);
  log ("test2", w);
  // close the writer and underlying file.
  w.close();
  // open and read the file.
  streamreader r = file.opentext("log.txt");
  dumplog (r);
  }

  public static void log (string logmessage, textwriter w)
  {
  w.write("rnlog entry : ");
  w.writeline("{0} {1}", datetime.now.tolongtimestring(),
  datetime.now.tolongdatestring());
  w.writeline(" :");
  w.writeline(" :{0}", logmessage);
  w.writeline ("-------------------------------");
  // update the underlying file.
  w.flush();
  }

  public static void dumplog (streamreader r)
  {
  // while not at the end of the file, read and write lines.
  string line;
  while ((line=r.readline())!=null)
  {
  console.writeline(line);
  }
  r.close();
  }
}


讀取檔案二

using (filestream fs = new filestream(file, filemode.open,fileaccess.readwrite))
            {
                xmldocument toxml = new xmldocument();
                toxml.load(fs);
                //do some modification for the xml.
                fs.flush();
                toxml.save(fs);
            }


更多詳細內容請查看:http://www.111cn.net/net/c/33608.htm


讀取檔案三

寫檔案

        public static void writefile(string filepath, string str)
        {
            streamwriter sr;
            if (file.exists(filepath)) //如果檔案存在,則建立file.appendtext對象
            {
                sr = file.appendtext(filepath);
             }
            else   //如果檔案不存在,則建立file.createtext對象
            {
                sr = file.createtext(filepath);
            } 
            sr.writeline(str);
            sr.close();
         }

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.