Write Byte array to File C# example
Today in this article we shall see the simple and easy approach of reading a large-size file and then Write a Byte array to File C# examples
We will see a generic approach that can be used to write a byte array to a file.
The discussed approach is very useful while dealing with large-size of files (.TXT or .CSV or .XLSX) like in GB or TB.
For demonstration purposes, I have used a very simple example here.
Today in this article, we will cover below aspects,
Read a file into a Byte array
Let’s first read a file as a byte array and then we will write a byte array to a file.
In the below example, we are reading the file using the FileStream Open method which lets you open FileStream on the specified path, with the specified mode, and read the file as a byte array.
private static void ReadFile(string filePath)
{
const int MAX_BUFFER = 1048576; //1MB
byte[] buffer = new byte[MAX_BUFFER];
int bytesRead;
int noOfFiles = 0;
using (FileStream fs = File.Open(filePath, FileMode.Open, FileAccess.Read))
using (BufferedStream bs = new BufferedStream(fs))
{
while ((bytesRead = bs.Read(buffer, 0, MAX_BUFFER)) != 0) //reading 1mb chunks at a time
{
}
}
}
Lets now write byte array to file,
Please note that the WriteAllBytes method will create a new file, writes the specified byte array to the file, and then closes the file also.
If the target file already exists, it is overwritten.
using (BufferedStream bs = new BufferedStream(fs))
{
while ((bytesRead = bs.Read(buffer, 0, MAX_BUFFER)) != 0) //reading 1mb chunks at a time
{
noOfFiles++;
//Let's create a small size file using the data. Or Pass this data for any further processing.
File.WriteAllBytes($"Test{noOfFiles}.txt", buffer);
}
}
References: Read a Large File in Chunks in C# -Part II
That’s all! Happy coding!
Does this help you fix your issue?
Do you have any better solutions or suggestions? Please sound off your comments below.
Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.