C# FileStream 按大小分段读取文本内容

来源:互联网 发布:网络安全工程师学什么 编辑:程序博客网 时间:2024/04/28 11:03

该例子首先在C盘根目录创建一个名为’file1.txt‘的文本文件。

然后再运行该例子。。


完整代码如下:

引入命名空间:

using System.IO;


完整代码:

namespace FileStreamRead{    class Program    {        static void Main(string[] args)        {            FileStream fs;            //获得文件所在路径            string filePath = "C:\\file1.txt";            //打开文件            try            {                fs = new FileStream(filePath, FileMode.Open);            }            catch(Exception)            {                throw;            }            //尚未读取的文件内容长度            long left = fs.Length;            //存储读取结果            byte[] bytes = new byte[100];            //每次读取长度            int maxLength = bytes.Length;            //读取位置            int start = 0;            //实际返回结果长度            int num = 0;            //当文件未读取长度大于0时,不断进行读取            while (left > 0)            {                fs.Position = start;                num = 0;                if (left < maxLength)                    num = fs.Read(bytes, 0, Convert.ToInt32(left));                else                    num = fs.Read(bytes, 0, maxLength);                if (num == 0)                    break;                start += num;                left -= num;                Console.WriteLine(Encoding.UTF8.GetString(bytes));            }            Console.WriteLine("end of file");            Console.ReadLine();            fs.Close();        }    }}


运行效果:


文本文件中的内容是 abc123


若以上有问题,可下载项目文件直接编译:

http://download.csdn.net/source/3465890

原创粉丝点击