Copiar Archivo De Origen A Archivo De Destino Usando Filestream En C#

Este programa copia un archivo de origen a un archivo de destino mediante FileStream en C#. El archivo se lee y escribe en bloques de 512 KB cada uno para gestionar archivos grandes de forma eficiente. El programa solicitará al usuario las rutas de los archivos de origen y destino. Verificará si el archivo de origen existe y gestionará los errores según corresponda. Si el archivo de destino ya existe, el programa avisará al usuario sin sobrescribirlo. El programa gestiona posibles problemas de acceso a los archivos, garantizando que el proceso de copia sea lo más robusto posible.

Grupo

Manejo de archivos en C#

Objectivo

1. Solicitar al usuario la ruta del archivo de origen.
2. Solicitar al usuario la ruta del archivo de destino.
3. Comprobar si el archivo de origen existe. De no ser así, mostrar un mensaje de error y cerrar el programa.
4. Si el archivo de destino ya existe, advertir al usuario y solicitar confirmación antes de sobrescribir.
5. Abrir el archivo de origen con FileStream y el archivo de destino en modo de escritura.
6. Copiar el contenido en bloques de 512 KB mediante un búfer.
7. Gestionar cualquier error durante la operación de copia del archivo.
8. Confirmar la finalización correcta del proceso de copia del archivo.

Crear un programa para copiar un archivo de origen a un archivo de destino. Debe usar FileStream y un tamaño de bloque de 512 KB. Un ejemplo de uso podría ser:

mycopy file.txt e:\file2.txt


El programa debe gestionar los casos en los que el archivo de origen no existe y debe advertir al usuario (pero no sobrescribir) si el archivo de destino ya existe.

Ejemplo de ejercicio en C#

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

class FileCopy
{
    // Main method to execute the file copying
    static void Main(string[] args)
    {
        // Prompt the user to enter the source file path
        Console.WriteLine("Please enter the source file path:");
        string sourcePath = Console.ReadLine();

        // Prompt the user to enter the destination file path
        Console.WriteLine("Please enter the destination file path:");
        string destPath = Console.ReadLine();

        // Check if the source file exists
        if (!File.Exists(sourcePath))
        {
            Console.WriteLine("The source file does not exist.");
            return; // Exit the program if the source file does not exist
        }

        // Check if the destination file already exists
        if (File.Exists(destPath))
        {
            Console.WriteLine("The destination file already exists.");
            Console.WriteLine("Do you want to overwrite it? (Y/N)");

            // Ask the user for confirmation to overwrite the file
            string overwriteConfirmation = Console.ReadLine().ToUpper();
            if (overwriteConfirmation != "Y")
            {
                Console.WriteLine("Operation cancelled. The destination file was not overwritten.");
                return; // Exit the program if the user does not want to overwrite
            }
        }

        try
        {
            // Open the source file with FileStream in read mode
            using (FileStream sourceStream = new FileStream(sourcePath, FileMode.Open, FileAccess.Read))
            {
                // Open the destination file with FileStream in write mode
                using (FileStream destStream = new FileStream(destPath, FileMode.Create, FileAccess.Write))
                {
                    // Define a buffer size of 512 KB
                    byte[] buffer = new byte[512 * 1024];

                    int bytesRead;
                    // Read the source file and write to the destination file in blocks of 512 KB
                    while ((bytesRead = sourceStream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        // Write the read block of data to the destination file
                        destStream.Write(buffer, 0, bytesRead);
                    }
                }
            }

            // Inform the user that the file has been copied successfully
            Console.WriteLine("File copied successfully!");
        }
        catch (Exception ex)
        {
            // Handle any errors that occur during the file copy process
            Console.WriteLine("An error occurred during the file copy process: " + ex.Message);
        }
    }
}

 Output

//Assuming the user runs the program and inputs the following paths:
Please enter the source file path:
C:\path\to\source\file.txt
Please enter the destination file path:
D:\path\to\destination\file2.txt

//If the source file exists and the destination does not already exist, the program will output:
File copied successfully!

//If the destination file already exists, the program will prompt:
The destination file already exists.
Do you want to overwrite it? (Y/N)

//If the user chooses 'Y', the program will proceed to copy the file, and the following message will be displayed:
File copied successfully!

//If the user chooses 'N', the program will output:
Operation cancelled. The destination file was not overwritten.

Comparte este ejercicio de C#