C#檔案讀寫初步

來源:互聯網
上載者:User
C#中讀寫檔案主要涉及到File,FileInfo,FileStream三個類,它們都是System.IO 的類,StreamReader是用於從流讀取和寫入流的類,使用之前都需using System.IO。

先定義一個TXT文檔路徑: string txtpath = (@"D:\url\livebaby.cn.txt") 要讀入這個文檔。

1)File 提供用於建立、複製、刪除、移動和開啟檔案的靜態方法,並協助建立 FileStream。

    FileStream fs = File.Open(txtpath, FileMode.Open);

    File可以直接調用各種方法(Open、Delete、Exists等)

    例如: if (File.Exists(txtpath))
            {
                File.Delete(txtpath);
            }

2)FileInfo 提供用於建立、複製、刪除、移動和開啟檔案的執行個體方法,並協助建立 FileStream。

    FileInfo fi = new FileInfo(txtpath); //執行個體化

    FileStream fs = fi.Open();

3)FileStream 支援通過其 Seek 方法隨機訪問檔案。預設情況下,FileStream 以同步方式開啟檔案,但它也支援非同步作業。

   利用FileStream 我們可以得到一個檔案的Streams,接著就是來讀取。

(4)StreamReader 通過使用 Encoding 進行字元和位元組的轉換,從 Streams 中讀取字元。

    StreamWriter 通過使用 Encoding 將字元轉換為位元組,向 Streams 寫入字元。

    StreamReader sr = new StreamReader(fs);

            string str = null;
            string temp=null;
            while((temp=sr.ReadLine())!=null)
            {
               str+=" "+temp;
            }

     得到一個字串,再可以對字串進行處理。

     TextReader 是 StreamReader 和 StringReader 的抽象基類。抽象 Stream 類的實現用於位元組輸入和輸出,而 TextReader 的實現用於 Unicode 字元輸出。

     TextWriter 是 StreamWriter 和 StringWriter 的抽象基類。抽象 Stream 類的實現用於位元組輸入和輸出,而 TextWriter 的實現用於 Unicode 字元輸出。

聯繫我們

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