最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

C#讀寫txt文件多種方法實(shí)例代碼

 更新時(shí)間:2013年11月27日 14:39:07   作者:  
這篇文章主要介紹了C#讀寫txt文件的小例子,大家可以參考使用

1.添加命名空

復(fù)制代碼 代碼如下:

System.IO;
System.Text;

2.文件的讀取

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

復(fù)制代碼 代碼如下:

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個(gè)參數(shù)是字節(jié)數(shù)組中開始寫入數(shù)據(jù)的位置,它通常是0,表示從數(shù)組的開端文件中向數(shù)組寫數(shù)據(jù),最后一個(gè)參數(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讀取文件,然后一行一行的輸出。

復(fù)制代碼 代碼如下:

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ù)寫入到文件里。

復(fù)制代碼 代碼如下:

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ù)寫入到文件。

復(fù)制代碼 代碼如下:

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

相關(guān)文章

最新評論

霞浦县| 鹤岗市| 贡觉县| 平顶山市| 湖南省| 长治市| 临湘市| 阳朔县| 惠州市| 迁西县| 江陵县| 晋江市| 紫阳县| 泗洪县| 景宁| 贵港市| 五华县| 汉沽区| 黄梅县| 柘荣县| 英德市| 波密县| 德安县| 阿拉尔市| 金山区| 杭锦后旗| 上犹县| 霞浦县| 亳州市| 饶阳县| 睢宁县| 贵德县| 新河县| 临邑县| 台山市| 华安县| 武清区| 邵东县| 新化县| 同心县| 凭祥市|