C# - Copying Binary Files
Copying files are often required in using computers. How about writing a C# program to copy the binary files. Note that binary file function can be used to copy the text file or any image files. However the files opened in text mode can not be used to copy binary files or image files.
Source Code
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static bool CopyBinaryFile(string srcfilename, string destfilename)
{
if (System.IO.File.Exists(srcfilename) == false)
{
Console.WriteLine("Could not find the Source file");
return false;
}
System.IO.Stream s1 = System.IO.File.Open(srcfilename, System.IO.FileMode.Open);
System.IO.Stream s2 = System.IO.File.Open(destfilename, System.IO.FileMode.Create);
System.IO.BinaryReader f1 = new System.IO.BinaryReader(s1);
System.IO.BinaryWriter f2 = new System.IO.BinaryWriter(s2);
while (true)
{
byte [] buf = new byte[10240];
int sz = f1.Read(buf, 0, 10240);
if (sz <= 0)
break;
f2.Write(buf, 0, sz);
if (sz < 10240)
break; // eof reached
}
f1.Close();
f2.Close();
return true;
}
static bool CopyTextFile(string srcfilename, string destfilename)
{
if (System.IO.File.Exists(srcfilename) == false)
{
Console.WriteLine("Could not find the Source file");
return false;
}
System.IO.StreamReader f1 = new System.IO.StreamReader(srcfilename);
System.IO.StreamWriter f2 = new System.IO.StreamWriter(destfilename);
while (true)
{
char[] buf = new char[1024];
int sz = f1.Read(buf, 0, 1024);
if (sz <= 0)
break;
f2.Write(buf, 0, sz);
if (sz < 1024)
break; // eof reached
}
f1.Close();
f2.Close();
return true;
}
static void Main(string[] args)
{
CopyBinaryFile("c:\\kathir.bmp", "c:\\kathir.bmp");
CopyTextFile("c:\\kathir.txt", "c:\\3.txt");
}
}
}
Output
None
|