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

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

然后再运行该例子。。


完整代码如下:

引入命名空间:

[csharp] view plain copy
 print?
  1. using System.IO;  


完整代码:

[csharp] view plain copy
 print?
  1. namespace FileStreamRead  
  2. {  
  3.     class Program  
  4.     {  
  5.         static void Main(string[] args)  
  6.         {  
  7.             FileStream fs;  
  8.             //获得文件所在路径  
  9.             string filePath = "C:\file1.txt";  
  10.   
  11.             //打开文件  
  12.             try  
  13.             {  
  14.                 fs = new FileStream(filePath, FileMode.Open);  
  15.             }  
  16.             catch(Exception)  
  17.             {  
  18.                 throw;  
  19.             }  
  20.   
  21.             //尚未读取的文件内容长度  
  22.             long left = fs.Length;  
  23.             //存储读取结果  
  24.             byte[] bytes = new byte[100];  
  25.             //每次读取长度  
  26.             int maxLength = bytes.Length;  
  27.             //读取位置  
  28.             int start = 0;  
  29.             //实际返回结果长度  
  30.             int num = 0;  
  31.             //当文件未读取长度大于0时,不断进行读取  
  32.             while (left > 0)  
  33.             {  
  34.                 fs.Position = start;  
  35.                 num = 0;  
  36.                 if (left < maxLength)  
  37.                     num = fs.Read(bytes, 0, Convert.ToInt32(left));  
  38.                 else  
  39.                     num = fs.Read(bytes, 0, maxLength);  
  40.                 if (num == 0)  
  41.                     break;  
  42.                 start += num;  
  43.                 left -= num;  
  44.                 Console.WriteLine(Encoding.UTF8.GetString(bytes));  
  45.             }  
  46.             Console.WriteLine("end of file");  
  47.             Console.ReadLine();  
  48.             fs.Close();  
  49.         }  
  50.     }  
  51. }  


运行效果:


文本文件中的内容是 abc123


原文地址:https://www.cnblogs.com/alan666/p/8312190.html