File copy program in C# With Programming Example



Copies an existing file to a new file. Overwriting a file of the same name is not allowed.

using System.IO;
using System;

namespace CSharpFilesAndStreams
{
	class CopyFile
	{
		static void Main(string[] args)
		{
			int i;
			FileStream fin = null;
			FileStream fout = null;
			if (args.Length != 2)
			{
				Console.WriteLine("Usage: CopyFile From To");
				return;
			}
			try
			{
				// Open the files.
				fin = new FileStream(args[0], FileMode.Open);
				fout = new FileStream(args[1], FileMode.Create);
				// Copy the file.
				do
				{
					i = fin.ReadByte();
					if (i != -1) fout.WriteByte((byte)i);
				} while (i != -1);
			}
			catch (IOException exc)
			{
				Console.WriteLine("I/O Error:\n" + exc.Message);
			}
			finally
			{
				if (fin != null) fin.Close();
				if (fout != null) fout.Close();
			}
		}
	}
}	

0 Comment's

Comment Form

Submit Comment