Introduction:
In this article, i am going to demonstrate how to create,read,write a binary file using C# 4.0.
Main:
When you open files in binary mode, you get back a stream that you can
control more precisely than with text.
See this below simple examble,
class Program
{
static void Main(string[] args)
{
if (args.Length < 2)
{
Console.WriteLine(
“Usage: FileCopy [SourceFile] [DestinationFile]”);
return;
}
string sourceFile = args[0];
string destFile = args[1];
const int BufferSize = 16384;
byte[] buffer = new byte[BufferSize];
int bytesCopied = 0;
UInt64 totalBytes = 0;
//open both files--the source file can be read shared, but not
//the destination
using (FileStream inStream = File.Open(
sourceFile, FileMode.Open,
FileAccess.Read, FileShare.Read))
using (FileStream outStream = File.Open(
destFile, FileMode.Create,
FileAccess.Write, FileShare.None))
{
do
{
//must track how many bytes we actually read in
bytesCopied = inStream.Read(buffer, 0, BufferSize);
if (bytesCopied > 0)
{
outStream.Write(buffer, 0, bytesCopied);
totalBytes += (UInt64)bytesCopied;
}
} while (bytesCopied > 0);
}
Console.WriteLine(“{0:N0} bytes copied”, totalBytes);
}
}
class Program { static void Main(string[] args) { if (args.Length < 2) { Console.WriteLine( “Usage: FileCopy [SourceFile] [DestinationFile]”); return; } string sourceFile = args[0]; string destFile = args[1]; const int BufferSize = 16384; byte[] buffer = new byte[BufferSize]; int bytesCopied = 0; UInt64 totalBytes = 0; //open both files--the source file can be read shared, but not //the destination using (FileStream inStream = File.Open( sourceFile, FileMode.Open, FileAccess.Read, FileShare.Read)) using (FileStream outStream = File.Open( destFile, FileMode.Create, FileAccess.Write, FileShare.None)) { do { //must track how many bytes we actually read in bytesCopied = inStream.Read(buffer, 0, BufferSize); if (bytesCopied > 0) { outStream.Write(buffer, 0, bytesCopied); totalBytes += (UInt64)bytesCopied; } } while (bytesCopied > 0); } Console.WriteLine(“{0:N0} bytes copied”, totalBytes); } } |
Conclusion:
Hope this helps,
Happy Coding.
Keep posting stuff like this i really like it
I found this post while surfing the net some random stuff. Thanks for sharing will be sure to follow this blog regularly and will email this post to my friends.
Really good blog post here and I just wanted to comment & thank you for posting this. I’ve bookmarked youi blog and I’ll be back to read more in the future my friend! Also nice colors on the layout, it’s really easy on the eyes.
Really great informative blog post here and I just wanted to comment & thank you for posting this. I’ve bookmarked youi blog and I’ll be back to read more in the future my friend! Also nice colors on the layout, it’s really easy on the eyes.