Ejercicio
Divisor De Archivos
Objectivo
Cree un programa para dividir un archivo (de cualquier tipo) en pedazos de cierto tamaño. ir debe recibir el nombre del archivo y el tamaño como parámetros. Por ejemplo, se puede usar escribiendo:
dividir myFile.exe 2000
Si el archivo "myFile.exe" tiene una longitud de 4500 bytes, ese comando produciría un archivo llamado "myFile.exe.001" de 2000 bytes de largo, otro llamado "myFile.exe.002" de 2000 bytes de largo y otro llamado "myFile.exe.003" de 500 bytes de largo.
Ejemplo Ejercicio C#
Mostrar Código C#
// 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
}
}
}
Salida
Sample input example.txt (original file):
This is an example file that will be split into chunks.
Compile and run the program with the following arguments:
FileSplitter example.txt 100
Assuming the original file has 156 bytes and the chunk size is 100 bytes, the file will be split into two parts.
Output files generated:
example.txt.001 (will contain the first 100 bytes)
example.txt.002 (will contain the remaining 56 bytes)
Content of example.txt.001 (first chunk):
This is an example file that will be
Content of example.txt.002 (second chunk):
split into chunks.
Console messages:
Created chunk example.txt.001 with 100 bytes.
Created chunk example.txt.002 with 56 bytes.
File split complete.
Código de Ejemplo Copiado!
Comparte este Ejercicio C# Sharp