Objective
Create a program to copy a source file to a destination file. You must use FileStream and a block size of 512 KB. An example usage might be:
mycopy file.txt e:\file2.txt
The program should handle cases where the source file does not exist, and it should warn the user (but not overwrite) if the destination file already exists.
Write Your C# Exercise
C# Exercise Example
// Import the necessary namespaces for file handling
using System;
using System.IO;
class FileCopier
{
// Main method where the program starts
static void Main(string[] args)
{
// Check if the user has provided the correct number of arguments
if (args.Length != 2)
{
Console.WriteLine("Usage: mycopy ");
return;
}
// Get the source and destination file paths from the command line arguments
string sourceFile = args[0];
string destinationFile = args[1];
// Check if the source file exists
if (!File.Exists(sourceFile))
{
Console.WriteLine("Error: The source file does not exist.");
return;
}
// Check if the destination file already exists
if (File.Exists(destinationFile))
{
Console.WriteLine("Warning: The destination file already exists. It will not be overwritten.");
return;
}
try
{
// Open the source file for reading
using (FileStream sourceStream = new FileStream(sourceFile, FileMode.Open, FileAccess.Read))
{
// Open the destination file for writing
using (FileStream destStream = new FileStream(destinationFile, FileMode.Create, FileAccess.Write))
{
// Set the block size to 512 KB
byte[] buffer = new byte[512 * 1024]; // 512 KB
int bytesRead;
// Read from the source file and write to the destination file in blocks of 512 KB
while ((bytesRead = sourceStream.Read(buffer, 0, buffer.Length)) > 0)
{
destStream.Write(buffer, 0, bytesRead);
}
Console.WriteLine("File copied successfully.");
}
}
}
catch (Exception ex)
{
// Catch any errors that occur during file operations
Console.WriteLine("An error occurred while copying the file: " + ex.Message);
}
}
}