C#讀寫檔案總結

來源:互聯網
上載者:User
1、使用FileStream讀寫檔案  檔案頭: using System;
using System.Collections.Generic;
using System.Text;
using System.IO;  讀檔案核心代碼: byte[] byData = new byte[100];
char[] charData = new char[1000];try
{
FileStream sFile = new FileStream("檔案路徑",FileMode.Open);
sFile.Seek(55, SeekOrigin.Begin);
sFile.Read(byData, 0, 100); //第一個參數是被傳進來的位元組數組,用以接受FileStream對象中的資料,第2個參數是位元組數組中開始寫入資料的位置,它通常是0,表示從數組的開端檔案中向數組寫資料,最後一個參數規定從檔案讀多少字元.
}
catch (IOException e)
{
Console.WriteLine("An IO exception has been thrown!");
Console.WriteLine(e.ToString());
Console.ReadLine();
return;
}
Decoder d = Encoding.UTF8.GetDecoder();
d.GetChars(byData, 0, byData.Length, charData, 0);
Console.WriteLine(charData);
Console.ReadLine();  寫檔案核心代碼: FileStream fs = new FileStream(檔案路徑,FileMode.Create);
//獲得位元組數組byte [] data =new UTF8Encoding().GetBytes(String);
//開始寫入
fs.Write(data,0,data.Length);//清空緩衝區、關閉流
fs.Flush();
fs.Close();  2、使用StreamReader和StreamWriter  檔案頭:  using System;
using System.Collections.Generic;
using System.Text;
using System.IO;  StreamReader讀取檔案: StreamReader objReader = new StreamReader(檔案路徑);
      string sLine="";
      ArrayList LineList = new ArrayList();    
      while (sLine != null)
      {
        sLine = objReader.ReadLine();
        if (sLine != null&&!sLine.Equals(""))
          LineList.Add(sLine);
      }
            objReader.Close();
            return LineList;  StreamWriter寫檔案:   FileStream fs = new FileStream(檔案路徑, FileMode.Create);
StreamWriter sw = new StreamWriter(fs);
//開始寫入
sw.Write(String);
 //清空緩衝區
sw.Flush();
//關閉流
sw.Close();
fs.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.