File.Copy Método

Definição

Copia um arquivo existente para um novo arquivo.

Sobrecargas

Copy(String, String, Boolean)

Copia um arquivo existente para um novo arquivo. É permitido substituir um arquivo de mesmo nome.

Copy(String, String)

Copia um arquivo existente para um novo arquivo. Não é permitida a substituição de um arquivo de mesmo nome.

Copy(String, String, Boolean)

Copia um arquivo existente para um novo arquivo. É permitido substituir um arquivo de mesmo nome.

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

O arquivo a ser copiado.

destFileName
String

O nome do arquivo de destino. Ele não pode ser um diretório.

overwrite
Boolean

true se o arquivo de destino deve ser substituído se ele já existir; caso contrário, false.

Exceções

O chamador não tem a permissão necessária.

- ou -

destFileName é somente leitura.

- ou -

overwrite é true, destFileName existe e está oculto, mas sourceFileName não está oculto.

sourceFileName ou destFileName é uma cadeia de caracteres de comprimento zero, contém somente espaços em branco ou um ou mais caracteres inválidos. Consulte caracteres inválidos usando o método GetInvalidPathChars().

- ou -

sourceFileName ou destFileName especifica um diretório.

sourceFileName ou destFileName é null.

O caminho especificado, o nome de arquivo, ou ambos excedem o tamanho máximo definido pelo sistema.

O caminho especificado em sourceFileName ou destFileName é inválido (por exemplo, está em uma unidade não mapeada).

sourceFileName não foi encontrado.

destFileName existe e overwrite é false.

- ou -

Ocorreu um erro de E/S.

sourceFileName ou destFileName está em um formato inválido.

Exemplos

O exemplo a seguir copia arquivos para a pasta de backup C:\archives\2008. Ele usa as duas sobrecargas do método da Copy seguinte maneira:

  • Primeiro, ele usa a sobrecarga de File.Copy(String, String) método para copiar arquivos de texto (.txt). O código demonstra que essa sobrecarga não permite substituir arquivos que já foram copiados.

Em seguida, ele usa a sobrecarga de File.Copy(String, String, Boolean) método para copiar imagens (arquivos .jpg). O código demonstra que essa sobrecarga permite substituir arquivos que já foram copiados.

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

Comentários

Os sourceFileName parâmetros e destFileName podem especificar informações de caminho relativas ou absolutas. As informações do caminho relativo são interpretadas como relativas ao diretório de trabalho atual. Esse método não dá suporte a caracteres curinga nos parâmetros.

Os atributos do arquivo original são retidos no arquivo copiado.

Para obter uma lista de tarefas comuns de E/S, consulte Tarefas comuns de E/S.

Confira também

Aplica-se a

Copy(String, String)

Copia um arquivo existente para um novo arquivo. Não é permitida a substituição de um arquivo de mesmo nome.

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

O arquivo a ser copiado.

destFileName
String

O nome do arquivo de destino. Não pode ser um diretório ou um arquivo existente.

Exceções

O chamador não tem a permissão necessária.

sourceFileName ou destFileName é uma cadeia de caracteres de comprimento zero, contém somente espaços em branco ou um ou mais caracteres inválidos. Consulte caracteres inválidos usando o método GetInvalidPathChars().

- ou -

sourceFileName ou destFileName especifica um diretório.

sourceFileName ou destFileName é null.

O caminho especificado, o nome de arquivo, ou ambos excedem o tamanho máximo definido pelo sistema.

O caminho especificado em sourceFileName ou destFileName é inválido (por exemplo, está em uma unidade não mapeada).

sourceFileName não foi encontrado.

destFileName existe.

- ou -

Ocorreu um erro de E/S.

sourceFileName ou destFileName está em um formato inválido.

Exemplos

O exemplo a seguir copia arquivos para a pasta de backup C:\archives\2008. Ele usa as duas sobrecargas do método da Copy seguinte maneira:

  • Primeiro, ele usa a sobrecarga de File.Copy(String, String) método para copiar arquivos de texto (.txt). O código demonstra que essa sobrecarga não permite substituir arquivos que já foram copiados.

  • Em seguida, ele usa a sobrecarga de File.Copy(String, String, Boolean) método para copiar imagens (arquivos .jpg). O código demonstra que essa sobrecarga permite substituir arquivos que já foram copiados.

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

Comentários

Esse método é equivalente à sobrecarga do Copy(String, String, Boolean) método com o overwrite parâmetro definido falsecomo .

Os sourceFileName parâmetros e destFileName podem especificar informações de caminho relativas ou absolutas. As informações do caminho relativo são interpretadas como relativas ao diretório de trabalho atual. Para obter o diretório de trabalho atual, consulte o Directory.GetCurrentDirectory método . Esse método não dá suporte a caracteres curinga nos parâmetros.

Os atributos do arquivo original são retidos no arquivo copiado.

Confira também

Aplica-se a