Programa Separador De Archivos En C#

Este programa permite dividir un archivo de cualquier tipo en fragmentos más pequeños de un tamaño específico. El programa toma dos parámetros: el nombre del archivo a dividir y el tamaño (en bytes) de cada fragmento. A continuación, creará varios archivos más pequeños con el mismo nombre que el archivo original, añadiendo un número de secuencia a cada fragmento. El programa es útil para gestionar archivos grandes que deben dividirse para facilitar su almacenamiento o transferencia. Por ejemplo, dividir un archivo de 4500 bytes en fragmentos de 2000 bytes generará tres archivos: los dos primeros tendrán 2000 bytes y el último los 500 bytes restantes.

Grupo

Manejo de archivos en C#

Objectivo

1. El programa requiere dos parámetros: el nombre del archivo y el tamaño (en bytes) de cada parte dividida.
2. El programa lee el archivo de entrada y lo divide en archivos más pequeños.
3. Genera archivos con el nombre original seguido de un número de secuencia (p. ej., file.exe.001, file.exe.002, etc.).
4. Si el tamaño del archivo no es divisible exactamente por el tamaño del fragmento especificado, el último archivo contendrá los datos restantes.
5. Utilice el siguiente formato para ejecutar el programa:

split myFile.exe 2000


Cree un programa para dividir un archivo (de cualquier tipo) en fragmentos de un tamaño determinado. Debe recibir el nombre del archivo y el tamaño como parámetros. Por ejemplo, se puede usar escribiendo:

split myFile.exe 2000


Si el archivo "myFile.exe" tiene una longitud de 4500 bytes, este comando generará un archivo llamado "myFile.exe.001" de 2000 bytes, otro archivo llamado "myFile.exe.002" de 2000 bytes y un tercer archivo llamado "myFile.exe.003" de 500 bytes.

Ejemplo de ejercicio en C#

 Copiar código C#
using System;
using System.IO;

class FileSplitter
{
    // Main method where the program starts execution
    static void Main(string[] args)
    {
        // Check if the user provided the correct number of arguments
        if (args.Length != 2)
        {
            Console.WriteLine("Usage: split  ");
            return;
        }

        // Get the input file name and chunk size from the arguments
        string inputFileName = args[0];
        int chunkSize;

        // Try to parse the chunk size to an integer
        if (!int.TryParse(args[1], out chunkSize) || chunkSize <= 0)
        {
            Console.WriteLine("Please enter a valid chunk size (positive integer).");
            return;
        }

        // Check if the input file exists
        if (!File.Exists(inputFileName))
        {
            Console.WriteLine("The specified file does not exist.");
            return;
        }

        try
        {
            // Open the input file using FileStream
            using (FileStream inputFile = new FileStream(inputFileName, FileMode.Open, FileAccess.Read))
            {
                // Get the total size of the input file
                long fileSize = inputFile.Length;

                // Calculate the number of chunks needed
                int chunkCount = (int)Math.Ceiling((double)fileSize / chunkSize);

                // Loop through and create the chunks
                for (int i = 0; i < chunkCount; i++)
                {
                    // Generate the name for the new chunked file (e.g., file.exe.001)
                    string outputFileName = $"{inputFileName}.{i + 1:D3}";

                    // Open the output file with FileStream to write the chunk
                    using (FileStream outputFile = new FileStream(outputFileName, FileMode.Create, FileAccess.Write))
                    {
                        // Calculate how many bytes to read in this chunk
                        int bytesToRead = (i < chunkCount - 1) ? chunkSize : (int)(fileSize - i * chunkSize);

                        // Buffer to hold the chunk data
                        byte[] buffer = new byte[bytesToRead];

                        // Read the data into the buffer
                        inputFile.Read(buffer, 0, bytesToRead);

                        // Write the buffer to the output file
                        outputFile.Write(buffer, 0, bytesToRead);
                    }

                    // Output progress message
                    Console.WriteLine($"Created: {outputFileName}");
                }

                // Indicate completion of the process
                Console.WriteLine("File split completed successfully.");
            }
        }
        catch (Exception ex)
        {
            // Handle any exceptions that may occur during file processing
            Console.WriteLine("An error occurred: " + ex.Message);
        }
    }
}

 Output

//For example, if you run the program on a file named myFile.exe of size 4500 bytes with a chunk size of 2000 bytes, the output files will be:
Created: myFile.exe.001
Created: myFile.exe.002
Created: myFile.exe.003
File split completed successfully.

Comparte este ejercicio de C#