File.Copy Método

Definición

Copia un archivo existente en un archivo nuevo.

Sobrecargas

Copy(String, String, Boolean)

Copia un archivo existente en un archivo nuevo. Se permite sobrescribir un archivo del mismo nombre.

Copy(String, String)

Copia un archivo existente en un archivo nuevo. No se permite sobrescribir un archivo del mismo nombre.

Copy(String, String, Boolean)

Source:
File.cs
Source:
File.cs
Source:
File.cs

Copia un archivo existente en un archivo nuevo. Se permite sobrescribir un archivo del mismo nombre.

public:
 static void Copy(System::String ^ sourceFileName, System::String ^ destFileName, bool overwrite);
public static void Copy (string sourceFileName, string destFileName, bool overwrite);
static member Copy : string * string * bool -> unit
Public Shared Sub Copy (sourceFileName As String, destFileName As String, overwrite As Boolean)

Parámetros

sourceFileName
String

Archivo que se va a copiar.

destFileName
String

Nombre del archivo de destino. No puede ser un directorio.

overwrite
Boolean

true si el archivo de destino debe reemplazarse si ya existe; de lo contrario, false.

Excepciones

El llamador no dispone del permiso requerido.

o bien

destFileName es de solo lectura.

o bien

overwrite es true, destFileName existe y está oculto, pero sourceFileName no está oculto.

sourceFileName o destFileName es una cadena de longitud cero que solo contiene espacios en blanco o uno o varios caracteres no válidos. Puede consultar los caracteres no válidos con el método GetInvalidPathChars().

O bien

sourceFileName o destFileName especifica un directorio.

sourceFileName o destFileName es null.

La ruta de acceso especificada, el nombre de archivo o ambos superan la longitud máxima definida por el sistema.

La ruta de acceso especificada en sourceFileName o destFileName no es válida (por ejemplo, está en una unidad no asignada).

No se encontró sourceFileName.

destFileName existe y overwrite es false.

o bien

Error de E/S.

sourceFileName o destFileName está en un formato no válido.

Ejemplos

En el ejemplo siguiente se copian los archivos en la carpeta de copia de seguridad C:\archives\2008. Usa las dos sobrecargas del método de la Copy siguiente manera:

  • En primer lugar, usa la sobrecarga del File.Copy(String, String) método para copiar archivos de texto (.txt). El código muestra que esta sobrecarga no permite sobrescribir archivos que ya se copiaron.

A continuación, usa la sobrecarga del File.Copy(String, String, Boolean) método para copiar imágenes (.jpg archivos). El código muestra que esta sobrecarga permite sobrescribir archivos que ya se copiaron.

string sourceDir = @"c:\current";
string backupDir = @"c:\archives\2008";

try
{
    string[] picList = Directory.GetFiles(sourceDir, "*.jpg");
    string[] txtList = Directory.GetFiles(sourceDir, "*.txt");

    // Copy picture files.
    foreach (string f in picList)
    {
        // Remove path from the file name.
        string fName = f.Substring(sourceDir.Length + 1);

        // Use the Path.Combine method to safely append the file name to the path.
        // Will overwrite if the destination file already exists.
        File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName), true);
    }

    // Copy text files.
    foreach (string f in txtList)
    {

        // Remove path from the file name.
        string fName = f.Substring(sourceDir.Length + 1);

        try
        {
            // Will not overwrite if the destination file already exists.
            File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName));
        }

        // Catch exception if the file was already copied.
        catch (IOException copyError)
        {
            Console.WriteLine(copyError.Message);
        }
    }

    // Delete source files that were copied.
    foreach (string f in txtList)
    {
        File.Delete(f);
    }
    foreach (string f in picList)
    {
        File.Delete(f);
    }
}

catch (DirectoryNotFoundException dirNotFound)
{
    Console.WriteLine(dirNotFound.Message);
}
let sourceDir = @"c:\current"
let backupDir = @"c:\archives\2008"

try
    let picList = Directory.GetFiles(sourceDir, "*.jpg")
    let txtList = Directory.GetFiles(sourceDir, "*.txt")

    // Copy picture files.
    for f in picList do
        // Remove path from the file name.
        let fName = f.Substring(sourceDir.Length + 1)

        // Use the Path.Combine method to safely append the file name to the path.
        // Will overwrite if the destination file already exists.
        File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName), true)

    // Copy text files.
    for f in txtList do
        // Remove path from the file name.
        let fName = f.Substring(sourceDir.Length + 1)

        try
            // Will not overwrite if the destination file already exists.
            File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName))

        // Catch exception if the file was already copied.
        with
        | :? IOException as copyError -> printfn $"{copyError.Message}"

    // Delete source files that were copied.
    for f in txtList do
        File.Delete f

    for f in picList do
        File.Delete f

// Catch exception if the file was already copied.
with
| :? DirectoryNotFoundException as dirNotFound -> printfn $"{dirNotFound.Message}"
Dim sourceDir As String = "c:\current"
Dim backupDir As String = "c:\archives\2008"

Try
    Dim picList As String() = Directory.GetFiles(sourceDir, "*.jpg")
    Dim txtList As String() = Directory.GetFiles(sourceDir, "*.txt")

    ' Copy picture files.
    For Each f As String In picList
        'Remove path from the file name.
        Dim fName As String = f.Substring(sourceDir.Length + 1)

        ' Use the Path.Combine method to safely append the file name to the path.
        ' Will overwrite if the destination file already exists.
        File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName), True)
    Next

    ' Copy text files.
    For Each f As String In txtList

        'Remove path from the file name.
        Dim fName As String = f.Substring(sourceDir.Length + 1)

        Try
            ' Will not overwrite if the destination file already exists.
            File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName))

            ' Catch exception if the file was already copied.
        Catch copyError As IOException
            Console.WriteLine(copyError.Message)
        End Try
    Next

    For Each f As String In txtList
        File.Delete(f)
    Next

    For Each f As String In picList
        File.Delete(f)
    Next

Catch dirNotFound As DirectoryNotFoundException
    Console.WriteLine(dirNotFound.Message)
End Try

Comentarios

Los sourceFileName parámetros y destFileName pueden especificar información de ruta de acceso relativa o absoluta. La información de ruta de acceso relativa se interpreta como relativa al directorio de trabajo actual. Este método no admite caracteres comodín en los parámetros.

Los atributos del archivo original se conservan en el archivo copiado.

Para obtener una lista de las tareas de E/S comunes, consulte Tareas de E/S comunes.

Consulte también

Se aplica a

Copy(String, String)

Source:
File.cs
Source:
File.cs
Source:
File.cs

Copia un archivo existente en un archivo nuevo. No se permite sobrescribir un archivo del mismo nombre.

public:
 static void Copy(System::String ^ sourceFileName, System::String ^ destFileName);
public static void Copy (string sourceFileName, string destFileName);
static member Copy : string * string -> unit
Public Shared Sub Copy (sourceFileName As String, destFileName As String)

Parámetros

sourceFileName
String

Archivo que se va a copiar.

destFileName
String

Nombre del archivo de destino. No puede ser un directorio o un archivo existente.

Excepciones

El llamador no dispone del permiso requerido.

sourceFileName o destFileName es una cadena de longitud cero que solo contiene espacios en blanco o uno o varios caracteres no válidos. Puede consultar los caracteres no válidos con el método GetInvalidPathChars().

O bien

sourceFileName o destFileName especifica un directorio.

sourceFileName o destFileName es null.

La ruta de acceso especificada, el nombre de archivo o ambos superan la longitud máxima definida por el sistema.

La ruta de acceso especificada en sourceFileName o destFileName no es válida (por ejemplo, está en una unidad no asignada).

No se encontró sourceFileName.

destFileName existe.

o bien

Error de E/S.

sourceFileName o destFileName está en un formato no válido.

Ejemplos

En el ejemplo siguiente se copian los archivos en la carpeta de copia de seguridad C:\archives\2008. Usa las dos sobrecargas del método de la Copy siguiente manera:

  • En primer lugar, usa la sobrecarga del File.Copy(String, String) método para copiar archivos de texto (.txt). El código muestra que esta sobrecarga no permite sobrescribir archivos que ya se copiaron.

  • A continuación, usa la sobrecarga del File.Copy(String, String, Boolean) método para copiar imágenes (.jpg archivos). El código muestra que esta sobrecarga permite sobrescribir archivos que ya se copiaron.

string sourceDir = @"c:\current";
string backupDir = @"c:\archives\2008";

try
{
    string[] picList = Directory.GetFiles(sourceDir, "*.jpg");
    string[] txtList = Directory.GetFiles(sourceDir, "*.txt");

    // Copy picture files.
    foreach (string f in picList)
    {
        // Remove path from the file name.
        string fName = f.Substring(sourceDir.Length + 1);

        // Use the Path.Combine method to safely append the file name to the path.
        // Will overwrite if the destination file already exists.
        File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName), true);
    }

    // Copy text files.
    foreach (string f in txtList)
    {

        // Remove path from the file name.
        string fName = f.Substring(sourceDir.Length + 1);

        try
        {
            // Will not overwrite if the destination file already exists.
            File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName));
        }

        // Catch exception if the file was already copied.
        catch (IOException copyError)
        {
            Console.WriteLine(copyError.Message);
        }
    }

    // Delete source files that were copied.
    foreach (string f in txtList)
    {
        File.Delete(f);
    }
    foreach (string f in picList)
    {
        File.Delete(f);
    }
}

catch (DirectoryNotFoundException dirNotFound)
{
    Console.WriteLine(dirNotFound.Message);
}
let sourceDir = @"c:\current"
let backupDir = @"c:\archives\2008"

try
    let picList = Directory.GetFiles(sourceDir, "*.jpg")
    let txtList = Directory.GetFiles(sourceDir, "*.txt")

    // Copy picture files.
    for f in picList do
        // Remove path from the file name.
        let fName = f.Substring(sourceDir.Length + 1)

        // Use the Path.Combine method to safely append the file name to the path.
        // Will overwrite if the destination file already exists.
        File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName), true)

    // Copy text files.
    for f in txtList do
        // Remove path from the file name.
        let fName = f.Substring(sourceDir.Length + 1)

        try
            // Will not overwrite if the destination file already exists.
            File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName))

        // Catch exception if the file was already copied.
        with
        | :? IOException as copyError -> printfn $"{copyError.Message}"

    // Delete source files that were copied.
    for f in txtList do
        File.Delete f

    for f in picList do
        File.Delete f

// Catch exception if the file was already copied.
with
| :? DirectoryNotFoundException as dirNotFound -> printfn $"{dirNotFound.Message}"
Dim sourceDir As String = "c:\current"
Dim backupDir As String = "c:\archives\2008"

Try
    Dim picList As String() = Directory.GetFiles(sourceDir, "*.jpg")
    Dim txtList As String() = Directory.GetFiles(sourceDir, "*.txt")

    ' Copy picture files.
    For Each f As String In picList
        'Remove path from the file name.
        Dim fName As String = f.Substring(sourceDir.Length + 1)

        ' Use the Path.Combine method to safely append the file name to the path.
        ' Will overwrite if the destination file already exists.
        File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName), True)
    Next

    ' Copy text files.
    For Each f As String In txtList

        'Remove path from the file name.
        Dim fName As String = f.Substring(sourceDir.Length + 1)

        Try
            ' Will not overwrite if the destination file already exists.
            File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName))

            ' Catch exception if the file was already copied.
        Catch copyError As IOException
            Console.WriteLine(copyError.Message)
        End Try
    Next

    For Each f As String In txtList
        File.Delete(f)
    Next

    For Each f As String In picList
        File.Delete(f)
    Next

Catch dirNotFound As DirectoryNotFoundException
    Console.WriteLine(dirNotFound.Message)
End Try

Comentarios

Este método es equivalente a la sobrecarga del Copy(String, String, Boolean) método con el overwrite parámetro establecido en false.

Los sourceFileName parámetros y destFileName pueden especificar información de ruta de acceso relativa o absoluta. La información de ruta de acceso relativa se interpreta como relativa al directorio de trabajo actual. Para obtener el directorio de trabajo actual, consulte el Directory.GetCurrentDirectory método . Este método no admite caracteres comodín en los parámetros.

Los atributos del archivo original se conservan en el archivo copiado.

Consulte también

Se aplica a