File Copier - C# Programming Exercise

This C# exercise involves creating a program that copies a source file to a destination file using a FileStream and a block size of 512 KB. The program should be able to handle different cases, such as when the source file does not exist or when the destination file already exists. If the destination file is already present, the program should warn the user but not overwrite the existing file.

Using 512 KB blocks is an efficient way to handle large files, as it allows data to be copied in smaller, more manageable chunks, improving the program's performance and reducing memory usage. This exercise will familiarize you with handling binary files in C# using FileStream, a type of data stream that provides efficient access to files.

The program should accept two parameters: the source file and the destination file. It should ensure that the source file exists and check if the destination file is already present, providing a warning if necessary. This exercise is useful for learning how to handle exceptions, how to work with large files using FileStream, and how to manage basic user interactions.

 Category

File Management

 Exercise

File Copier

 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

// 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);
        }
    }
}

 Share this C# exercise

 More C# Programming Exercises of File Management

Explore our set of C# programming exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C#. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C#.

  •  MP3 reader

    This C# exercise is about the ID3 specifications, which apply to any file or audiovisual container, but are primarily used with audio containers. There are three comp...

  •  C to C# converter

    This exercise consists of creating a program that converts simple C programs, such as the following one, into C#, ensuring that the resulting program compiles ...

  •  File splitter

    This exercise involves creating a program that splits a file (of any kind) into pieces of a certain size. The program should receive the file name and the desired size of th...

  •  Encrypt a BMP file

    This exercise involves creating a program to encrypt and decrypt a BMP image file by changing the "BM" mark in the first two bytes to "MB" and vice versa. The program should...

  •  CSV converter

    This exercise involves creating a program that reads a CSV file with four data blocks (three text fields and one numeric) separated by commas, and generates a text file wher...

  •  File comparer

    This exercise involves creating a C# program that determines if two files (of any kind) are identical, meaning they have the same content. The program should c...