当前位置: 移动技术网 > IT编程>开发语言>c# > C#读写txt文件的2种方法

C#读写txt文件的2种方法

2019年07月18日  | 移动技术网IT编程  | 我要评论

本文实例为大家分享了c#读取与写入txt文本文档数据的具体代码,供大家参考,具体内容如下

1.添加命名空间

  system.io;

  system.text;

2.文件的读取

(1).使用filestream类进行文件的读取,并将它转换成char数组,然后输出。

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传进来的字节数组,用以接受filestream对象中的数据,第2个参数是字节数组中开始写入数据的位置,它通常是0,表示从数组的开端文件中向数组写数据,最后一个参数规定从文件读多少字符.
        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类创建文件,然后将数据写入到文件里。

public void write()
    {
      filestream fs = new filestream("e:\\ak.txt", filemode.create);
      //获得字节数组
      byte[] data = system.text.encoding.default.getbytes("hello world!"); 
      //开始写入
      fs.write(data, 0, data.length);
      //清空缓冲区、关闭流
      fs.flush();
      fs.close();
    }

(2).使用filestream类创建文件,使用streamwriter类,将数据写入到文件。

public void write(string path)
    {
      filestream fs = new filestream(path, filemode.create);
      streamwriter sw = new streamwriter(fs);
      //开始写入
      sw.write("hello world!!!!");
      //清空缓冲区
      sw.flush();
      //关闭流
      sw.close();
      fs.close();
    }

以上就完成了,txt文本文档的数据读取与写入。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网