其他分享
首页 > 其他分享> > 分批读取大文件

分批读取大文件

作者:互联网

public static void Show3()
{
string LogPath = ConfigurationManager.AppSettings["LogPath"];
FileStream fs;
//获得文件所在路径
//string filePath = "D:\\study\\朝夕\01架构师资源\\高级班12期\\20190116Advanced12Course19IOSerialize\\IOSerialize\\IOSerialize\\Log\\testlog.txt";
string filePath = Path.Combine(LogPath, "testlog.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();
}

标签:文件,fs,Console,读取,分批,bytes,num,left
来源: https://www.cnblogs.com/csj007523/p/14800909.html