File.Copy Método

Definição

Copia um ficheiro existente para um novo ficheiro.

Sobrecargas

Name Description
Copy(String, String)

Copia um ficheiro existente para um novo ficheiro. Não é permitido sobrescrever um ficheiro com o mesmo nome.

Copy(String, String, Boolean)

Copia um ficheiro existente para um novo ficheiro. É permitido sobrescrever um ficheiro com o mesmo nome.

Copy(String, String)

Copia um ficheiro existente para um novo ficheiro. Não é permitido sobrescrever um ficheiro com o 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 ficheiro para copiar.

destFileName
String

O nome do ficheiro de destino. Isto não pode ser um diretório ou um ficheiro existente.

Exceções

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

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

-ou-

sourceFileName ou destFileName especifica um diretório.

sourceFileName ou destFileName é null.

O caminho especificado, nome do ficheiro ou ambos excedem o comprimento máximo definido pelo sistema.

O caminho especificado em sourceFileName ou destFileName é inválido (por exemplo, está num disco não mapeado).

sourceFileName não foi encontrado.

destFileName existe.

-ou-

Ocorreu um erro de E/S.

sourceFileName ou destFileName está num formato inválido.

Exemplos

O exemplo seguinte copia ficheiros para a pasta de backup C:\archives\2008. Utiliza as duas sobrecargas do Copy método da seguinte forma:

  • Primeiro utiliza a File.Copy(String, String) sobrecarga de métodos para copiar ficheiros de texto (.txt). O código demonstra que esta sobrecarga não permite sobrescrever ficheiros que já foram copiados.

  • Depois, utiliza o File.Copy(String, String, Boolean) método overload para copiar imagens (.jpg ficheiros). O código demonstra que esta sobrecarga permite sobrescrever ficheiros 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

Observações

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

Os sourceFileName parâmetros e destFileName podem especificar informação relativa ou absoluta do caminho. A informação relativa do caminho é interpretada como relativa ao diretório de trabalho atual. Para obter o diretório de trabalho atual, consulte o Directory.GetCurrentDirectory método. Este método não suporta caracteres coringa nos parâmetros.

Os atributos do ficheiro original são mantidos no ficheiro copiado.

Ver também

Aplica-se a

Copy(String, String, Boolean)

Copia um ficheiro existente para um novo ficheiro. É permitido sobrescrever um ficheiro com o 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 ficheiro para copiar.

destFileName
String

O nome do ficheiro de destino. Isto não pode ser um diretório.

overwrite
Boolean

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

Exceções

O interlocutor 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 comprimento zero, contém apenas espaços em branco, ou contém um ou mais caracteres inválidos. Pode consultar caracteres inválidos usando o GetInvalidPathChars() método.

-ou-

sourceFileName ou destFileName especifica um diretório.

sourceFileName ou destFileName é null.

O caminho especificado, nome do ficheiro ou ambos excedem o comprimento máximo definido pelo sistema.

O caminho especificado em sourceFileName ou destFileName é inválido (por exemplo, está num disco não mapeado).

sourceFileName não foi encontrado.

destFileName existe e overwrite é false.

-ou-

Ocorreu um erro de E/S.

sourceFileName ou destFileName está num formato inválido.

Exemplos

O exemplo seguinte copia ficheiros para a pasta de backup C:\archives\2008. Utiliza as duas sobrecargas do Copy método da seguinte forma:

  • Primeiro utiliza a File.Copy(String, String) sobrecarga de métodos para copiar ficheiros de texto (.txt). O código demonstra que esta sobrecarga não permite sobrescrever ficheiros que já foram copiados.

Depois, utiliza o File.Copy(String, String, Boolean) método overload para copiar imagens (.jpg ficheiros). O código demonstra que esta sobrecarga permite sobrescrever ficheiros 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

Observações

Os sourceFileName parâmetros e destFileName podem especificar informação relativa ou absoluta do caminho. A informação relativa do caminho é interpretada como relativa ao diretório de trabalho atual. Este método não suporta caracteres coringa nos parâmetros.

Os atributos do ficheiro original são mantidos no ficheiro copiado.

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

Ver também

Aplica-se a