File Copy with FileStream
In this chapter you will learn:
Copy a file with FileStream
using System; // java 2 s . c o m
using System.IO;
class MainClass {
public static void Main(string[] args) {
int i;
FileStream fin;
FileStream fout;
try {
fin = new FileStream("inputFile.txt", FileMode.Open);
} catch(FileNotFoundException exc) {
Console.WriteLine(exc.Message + "\nInput File Not Found");
return;
}
try {
fout = new FileStream("outputFile.txt", FileMode.Create);
} catch(IOException exc) {
Console.WriteLine(exc.Message + "\nError Opening Output File");
return;
}
try {
do {
i = fin.ReadByte();
if(i != -1)
fout.WriteByte((byte)i);
} while(i != -1);
} catch(IOException exc) {
Console.WriteLine(exc.Message + "File Error");
}
fin.Close();
fout.Close();
}
}
Copy a file using byte array
using System;// j a v a 2 s. c om
using System.IO;
using System.IO.Compression;
public class MainClass
{
public static void Main()
{
using (Stream from = new FileStream("c:\\test.txt", FileMode.Open))
using (Stream to = new FileStream("c:\\test2.txt", FileMode.OpenOrCreate))
{
int readCount;
byte[] buffer = new byte[1024];
while ((readCount = from.Read(buffer, 0, 1024)) != 0)
{
to.Write(buffer, 0, readCount);
}
}
}
}
Next chapter...
What you will learn in the next chapter: