当前位置: 移动技术网 > IT编程>开发语言>c# > C#使用FileStream循环读取大文件数据的方法示例

C#使用FileStream循环读取大文件数据的方法示例

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

本文实例讲述了c#使用filestream循环读取大文件数据的方法。分享给大家供大家参考,具体如下:

今天学习了filestream的用法,用来读取文件流,教程上都是读取小文件,一次性读取,但是如果遇到大文件,那么我们就需要循环读取文件。

直接上代码。

引用命名空间

using system.io;

下面就是循环读取大文件的代码

class program
{
    static void main(string[] args)
    {
      //循环读取大文本文件
      filestream fsread;
      //获取文件路径
      string filepath="c:\\users\\国兴\\desktop\\1号店账号.txt";
      //用filestream文件流打开文件
      try
      {
        fsread = new filestream(@filepath,filemode.open);
      }
      catch (exception)
      {
        throw;
      }
      //还没有读取的文件内容长度
      long leftlength = fsread.length;
      //创建接收文件内容的字节数组
      byte[] buffer = new byte[1024];
      //每次读取的最大字节数
      int maxlength=buffer.length;
      //每次实际返回的字节数长度
      int num=0;
      //文件开始读取的位置
      int filestart=0;
      while (leftlength>0)
      {
        //设置文件流的读取位置
        fsread.position=filestart;
        if (leftlength<maxlength)
        {
          num=fsread.read(buffer,0,convert.toint32(leftlength));
        }
        else{
          num=fsread.read(buffer,0,maxlength);
        }
        if (num==0)
        {
          break;
        }
        filestart += num;
        leftlength -= num;
        console.writeline(encoding.default.getstring(buffer));
      }
      console.writeline("end of line");
      fsread.close();
      console.readkey();
    }
}

更多关于c#相关内容感兴趣的读者可查看本站专题:《c#文件操作常用技巧汇总》、《c#遍历算法与技巧总结》、《c#程序设计之线程使用技巧总结》、《c#操作excel技巧总结》、《c#中xml文件操作技巧汇总》、《c#常见控件用法教程》、《winform控件用法总结》、《c#数据结构与算法教程》、《c#数组操作技巧总结》及《c#面向对象程序设计入门教程

希望本文所述对大家c#程序设计有所帮助。

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

相关文章:

验证码:
移动技术网