Example Method for C to Read Large File Data Using FileStream Loop
- 2021-12-13 16:45:53
- OfStack
This article illustrates how C # uses FileStream loop to read large file data. Share it for your reference, as follows:
Today, I learned the usage of FileStream, which is used to read the file stream. In the tutorial, I read small files once, but if I encounter large files, we need to read the files cyclically.
Go directly to the code.
Reference namespace
using System.IO;
The following is the code to read a large file in a loop
class Program
{
static void Main(string[] args)
{
// Loop to read large text files
FileStream fsRead;
// Get the file path
string filePath="C:\\Users\\ Guo Xing \\Desktop\\1 Number shop account number .txt";
// Use FileStream File stream opens a file
try
{
fsRead = new FileStream(@filePath,FileMode.Open);
}
catch (Exception)
{
throw;
}
// Length of file content that has not been read yet
long leftLength = fsRead.Length;
// Create a byte array to receive the contents of the file
byte[] buffer = new byte[1024];
// Maximum number of bytes per read
int maxLength=buffer.Length;
// The actual number of bytes returned each time
int num=0;
// The location where the file begins to be read
int fileStart=0;
while (leftLength>0)
{
// Set the read location of the file stream
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();
}
}
More readers interested in C # can check the topic of this site: "C # File Operation Skills Summary", "C # Traversal Algorithm and Skills Summary", "C # Programming Thread Use Skills Summary", "C # Operating Excel Skills Summary", "XML File Operation Skills Summary in C #", "C # Common Control Usage Tutorial", "WinForm Control Usage Summary", "C # Data Structure and Algorithm Tutorial", "C # Array Operation Skills Summary" and "C # Object-Oriented Programming Introduction Tutorial"
I hope this article is helpful to everyone's C # programming.