File.Copy Metodo

Definizione

Copia un file esistente in un nuovo file.

Overload

Copy(String, String, Boolean)

Copia un file esistente in un nuovo file. È consentito sovrascrivere un file con lo stesso nome.

Copy(String, String)

Copia un file esistente in un nuovo file. Non è consentito sovrascrivere un file con lo stesso nome.

Copy(String, String, Boolean)

Origine:
File.cs
Origine:
File.cs
Origine:
File.cs

Copia un file esistente in un nuovo file. È consentito sovrascrivere un file con lo stesso 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)

Parametri

sourceFileName
String

File da copiare.

destFileName
String

Nome del file di destinazione. Non può essere una directory.

overwrite
Boolean

true se il file di destinazione deve essere sostituito se esiste già; in caso contrario, false.

Eccezioni

Il chiamante non dispone dell'autorizzazione richiesta.

-oppure-

destFileName è di sola lettura.

-oppure-

overwrite è true, destFileName esiste ed è nascosto, ma sourceFileName non è nascosto.

sourceFileName o destFileName è una stringa di lunghezza zero, contiene solo spazi vuoti o contiene uno o più caratteri non validi. È possibile cercare i caratteri non validi usando il metodo GetInvalidPathChars().

-oppure-

sourceFileName o destFileName specifica una directory.

sourceFileName o destFileName è null.

Il percorso specificato, il nome file o entrambi superano la lunghezza massima definita dal sistema.

Il percorso specificato in sourceFileName o destFileName non è valido (ad esempio si trova in un'unità non mappata).

Il parametro sourceFileName non è stato trovato.

destFileName esiste e overwrite è false.

-oppure-

Si è verificato un errore di I/O.

Il formato di sourceFileName o destFileName non è valido.

Esempio

Nell'esempio seguente copia file cartella di backup c:\archives\2008. Usa i due overload del Copy metodo come segue:

  • Usa innanzitutto l'overload del File.Copy(String, String) metodo per copiare i file di testo (.txt). Il codice dimostra che questo overload non consente di sovrascrivere i file già copiati.

Usa quindi l'overload del File.Copy(String, String, Boolean) metodo per copiare immagini (.jpg file). Il codice dimostra che questo overload consente di sovrascrivere i file già copiati.

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

Commenti

I sourceFileName parametri e destFileName possono specificare informazioni relative o assolute sul percorso. Le informazioni relative sul percorso sono interpretate come relative alla directory di lavoro corrente. Questo metodo non supporta caratteri jolly nei parametri.

Gli attributi del file originale vengono conservati nel file copiato.

Per un elenco di attività di I/O comuni, vedere Attività di I/O comuni.

Vedi anche

Si applica a

Copy(String, String)

Origine:
File.cs
Origine:
File.cs
Origine:
File.cs

Copia un file esistente in un nuovo file. Non è consentito sovrascrivere un file con lo stesso 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)

Parametri

sourceFileName
String

File da copiare.

destFileName
String

Nome del file di destinazione. Non può essere una directory o un file esistente.

Eccezioni

Il chiamante non dispone dell'autorizzazione richiesta.

sourceFileName o destFileName è una stringa di lunghezza zero, contiene solo spazi vuoti o contiene uno o più caratteri non validi. È possibile cercare i caratteri non validi usando il metodo GetInvalidPathChars().

-oppure-

sourceFileName o destFileName specifica una directory.

sourceFileName o destFileName è null.

Il percorso specificato, il nome file o entrambi superano la lunghezza massima definita dal sistema.

Il percorso specificato in sourceFileName o destFileName non è valido (ad esempio si trova in un'unità non mappata).

Il parametro sourceFileName non è stato trovato.

L'oggetto destFileName esiste.

-oppure-

Si è verificato un errore di I/O.

Il formato di sourceFileName o destFileName non è valido.

Esempio

Nell'esempio seguente copia file cartella di backup c:\archives\2008. Usa i due overload del Copy metodo come segue:

  • Usa innanzitutto l'overload del File.Copy(String, String) metodo per copiare i file di testo (.txt). Il codice dimostra che questo overload non consente di sovrascrivere i file già copiati.

  • Usa quindi l'overload del File.Copy(String, String, Boolean) metodo per copiare immagini (.jpg file). Il codice dimostra che questo overload consente di sovrascrivere i file già copiati.

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

Commenti

Questo metodo equivale all'overload del Copy(String, String, Boolean) metodo con il overwrite parametro impostato su false.

I sourceFileName parametri e destFileName possono specificare informazioni relative o assolute sul percorso. Le informazioni relative sul percorso sono interpretate come relative alla directory di lavoro corrente. Per ottenere la directory di lavoro corrente, vedere il Directory.GetCurrentDirectory metodo . Questo metodo non supporta caratteri jolly nei parametri.

Gli attributi del file originale vengono conservati nel file copiato.

Vedi anche

Si applica a