欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#讀寫txt文件的2種方法

 更新時間:2017年10月18日 11:51:39   作者:Jerron Lu  
這篇文章主要為大家詳細(xì)介紹了C#讀寫txt文本文檔數(shù)據(jù)的2種方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下

本文實例為大家分享了C#讀取與寫入txt文本文檔數(shù)據(jù)的具體代碼,供大家參考,具體內(nèi)容如下

1.添加命名空間

  System.IO;

  System.Text;

2.文件的讀取

(1).使用FileStream類進(jìn)行文件的讀取,并將它轉(zhuǎn)換成char數(shù)組,然后輸出。

byte[] byData = new byte[100];
    char[] charData = new char[1000];
    public void Read()
    {
      try
      {
        FileStream file = new FileStream("E:\\test.txt", FileMode.Open);
        file.Seek(0, SeekOrigin.Begin);
        file.Read(byData, 0, 100); 
        //byData傳進(jìn)來的字節(jié)數(shù)組,用以接受FileStream對象中的數(shù)據(jù),第2個參數(shù)是字節(jié)數(shù)組中開始寫入數(shù)據(jù)的位置,它通常是0,表示從數(shù)組的開端文件中向數(shù)組寫數(shù)據(jù),最后一個參數(shù)規(guī)定從文件讀多少字符.
        Decoder d = Encoding.Default.GetDecoder();
        d.GetChars(byData, 0, byData.Length, charData, 0);
        Console.WriteLine(charData);
        file.Close();
      }
      catch (IOException e)
      {
        Console.WriteLine(e.ToString());
      }
    }

(2).使用StreamReader讀取文件,然后一行一行的輸出。

public void Read(string path)
    {
      StreamReader sr = new StreamReader(path,Encoding.Default);
      String line;
      while ((line = sr.ReadLine()) != null) 
      {
        Console.WriteLine(line.ToString());
      }
    }

3.文件的寫入

(1).使用FileStream類創(chuàng)建文件,然后將數(shù)據(jù)寫入到文件里。

public void Write()
    {
      FileStream fs = new FileStream("E:\\ak.txt", FileMode.Create);
      //獲得字節(jié)數(shù)組
      byte[] data = System.Text.Encoding.Default.GetBytes("Hello World!"); 
      //開始寫入
      fs.Write(data, 0, data.Length);
      //清空緩沖區(qū)、關(guān)閉流
      fs.Flush();
      fs.Close();
    }

(2).使用FileStream類創(chuàng)建文件,使用StreamWriter類,將數(shù)據(jù)寫入到文件。

public void Write(string path)
    {
      FileStream fs = new FileStream(path, FileMode.Create);
      StreamWriter sw = new StreamWriter(fs);
      //開始寫入
      sw.Write("Hello World!!!!");
      //清空緩沖區(qū)
      sw.Flush();
      //關(guān)閉流
      sw.Close();
      fs.Close();
    }

以上就完成了,txt文本文檔的數(shù)據(jù)讀取與寫入。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論