File Splitter - C# Programming Exercise

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 the pieces as parameters. For example, when running the command: split myFile.exe 2000, and the file "myFile.exe" is 4500 bytes long, the program should create three files: one named "myFile.exe.001" of 2000 bytes, another named "myFile.exe.002" also of 2000 bytes, and a third file "myFile.exe.003" containing the remaining 500 bytes. This exercise tests the ability to work with binary files and efficiently handle their division while ensuring the content is preserved and can be correctly reassembled.

 Category

File Management

 Exercise

File Splitter

 Objective

Create a program to split a file (of any kind) into pieces of a certain size. It must receive the name of the file and the size as parameters. For example, it can be used by typing:

split myFile.exe 2000

If the file "myFile.exe" is 4500 bytes long, that command would produce a file named "myFile.exe.001" that is 2000 bytes long, another file named "myFile.exe.002" that is also 2000 bytes long, and a third file named "myFile.exe.003" that is 500 bytes long.

 Write Your C# Exercise

// Import the necessary namespaces for file handling and system operations
using System; // System namespace for basic input/output operations
using System.IO; // For file handling functions like FileStream
using System.Text; // For encoding and byte handling

class FileSplitter // Main class for the file splitting program
{
    static void Main(string[] args) // Entry point of the program
    {
        // Check if two arguments are provided (the file path and the size)
        if (args.Length != 2) // Check if the number of arguments is incorrect
        {
            Console.WriteLine("Usage: FileSplitter  "); // Display usage instructions
            return; // Exit the program if arguments are not correct
        }

        string fileName = args[0]; // Get the file name from the first argument
        int chunkSize; // Declare a variable for chunk size
        bool isNumeric = Int32.TryParse(args[1], out chunkSize); // Try to convert the second argument to an integer for the chunk size

        // Validate that the chunk size is a positive number
        if (!isNumeric || chunkSize <= 0) // If the chunk size is not valid or non-positive
        {
            Console.WriteLine("Error: Chunk size must be a positive number."); // Inform the user about the error
            return; // Exit the program if the chunk size is invalid
        }

        // Check if the file exists
        if (!File.Exists(fileName)) // If the file doesn't exist
        {
            Console.WriteLine("Error: The file does not exist."); // Inform the user about the missing file
            return; // Exit the program if the file is missing
        }

        try
        {
            // Open the source file for reading
            using (FileStream inputFile = new FileStream(fileName, FileMode.Open, FileAccess.Read)) // Open the file in read-only mode
            {
                long fileLength = inputFile.Length; // Get the length of the file in bytes
                int chunkCount = (int)(fileLength / chunkSize); // Calculate how many full chunks will be created
                if (fileLength % chunkSize != 0) chunkCount++; // If there is a remainder, add one more chunk

                byte[] buffer = new byte[chunkSize]; // Create a buffer to store chunks of the file
                int bytesRead; // Variable to store the number of bytes read at a time

                // Loop through the file and create the chunks
                for (int i = 0; i < chunkCount; i++) // Loop over each chunk
                {
                    string outputFileName = $"{fileName}.{i + 1:D3}"; // Generate the output file name (e.g., myFile.exe.001, myFile.exe.002, etc.)

                    // Open a new file to write the current chunk
                    using (FileStream outputFile = new FileStream(outputFileName, FileMode.Create, FileAccess.Write)) // Open the output file in write mode
                    {
                        // Calculate how many bytes to read for the current chunk
                        bytesRead = inputFile.Read(buffer, 0, chunkSize); // Read the next chunk of the file

                        // Write the chunk to the output file
                        outputFile.Write(buffer, 0, bytesRead); // Write the read bytes to the new file
                    }

                    Console.WriteLine($"Created chunk {outputFileName} with {bytesRead} bytes."); // Notify the user about the chunk created
                }
            }

            Console.WriteLine("File split complete."); // Inform the user that the splitting is complete
        }
        catch (Exception ex) // Catch any exceptions that occur during the file handling
        {
            Console.WriteLine($"An error occurred: {ex.Message}"); // Display the error 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#.

  •  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...

  •  Display BPM on console

    This exercise involves creating a C# program to decode an image file in the Netpbm format (specifically, the P1 format, which is for black and white ima...

  •  PCX width and height

    This exercise involves creating a C# program to check if a file is a PCX image and, if so, extract and display the image's dimensions (width and height). To do...

  •  Extract text from a binary file

    This exercise involves creating a C# program that extracts only the alphabetic characters contained in a binary file and dumps them to a separate file. The program sh...