FileInfo.CopyTo Méthode

Définition

Copie un fichier existant dans un nouveau fichier.

Surcharges

Nom Description
CopyTo(String)

Copie un fichier existant dans un nouveau fichier, ce qui interdit le remplacement d’un fichier existant.

CopyTo(String, Boolean)

Copie un fichier existant dans un nouveau fichier, ce qui permet le remplacement d’un fichier existant.

CopyTo(String)

Source:
FileInfo.cs
Source:
FileInfo.cs
Source:
FileInfo.cs
Source:
FileInfo.cs
Source:
FileInfo.cs

Copie un fichier existant dans un nouveau fichier, ce qui interdit le remplacement d’un fichier existant.

public:
 System::IO::FileInfo ^ CopyTo(System::String ^ destFileName);
public System.IO.FileInfo CopyTo(string destFileName);
member this.CopyTo : string -> System.IO.FileInfo
Public Function CopyTo (destFileName As String) As FileInfo

Paramètres

destFileName
String

Nom du nouveau fichier à copier.

Retours

Un nouveau fichier avec un chemin complet.

Exceptions

.NET Framework et les versions .NET Core antérieures à la version 2.1 : destFileName est vide, contient uniquement des espaces blancs ou contient des caractères non valides.

Une erreur se produit ou le fichier de destination existe déjà.

L’appelant n’a pas l’autorisation requise.

destFileName a la valeur null.

Un chemin d’accès au répertoire est transmis, ou le fichier est déplacé vers un autre lecteur.

Le répertoire spécifié dans destFileName n’existe pas.

Le chemin d’accès spécifié, le nom de fichier ou les deux dépassent la longueur maximale définie par le système.

destFileName contient un signe deux-points (:) dans la chaîne, mais ne spécifie pas le volume.

Exemples

L’exemple suivant illustre les deux surcharges de la CopyTo méthode.

using System;
using System.IO;

class Test
{

    public static void Main()
    {
        string path = @"c:\SoureFile.txt";
        string path2 = @"c:\NewFile.txt";
        FileInfo fi1 = new FileInfo(path);
        FileInfo fi2 = new FileInfo(path2);

        try
        {
            // Create the source file.
            using (FileStream fs = fi1.Create()) { }

            //Ensure that the target file does not exist.
            if (File.Exists(path2))
            {
                fi2.Delete();
            }

            //Copy the file.f
            fi1.CopyTo(path2);
            Console.WriteLine("{0} was copied to {1}.", path, path2);
        }
        catch (IOException ioex)
        {
            Console.WriteLine(ioex.Message);
        }
    }
}
Imports System.IO

Public Class Test

    Public Shared Sub Main()
        'Specify the directories you want to manipulate.
        Dim path As String = "c:\SourceFile.txt"
        Dim path2 As String = "c:\NewFile.txt"
        Dim fi As FileInfo = New FileInfo(path)
        Dim fi2 As FileInfo = New FileInfo(path2)

        Try
            Using fs As FileStream = fi.Create()
            End Using

            'Ensure that the target does not exist.
            If File.Exists(path2) Then
                fi2.Delete()
            End If
            
            'Copy the file.
            fi.CopyTo(path2)
            Console.WriteLine("{0} was copied to {1}.", path, path2)

        Catch ioex As IOException
            Console.WriteLine(ioex.Message)
        End Try
    End Sub
End Class

L’exemple suivant illustre la copie d’un fichier dans un autre fichier, lève une exception si le fichier de destination existe déjà.

using System;
using System.IO;

public class CopyToTest
{
    public static void Main()
    {
        try
        {
            // Create a reference to a file, which might or might not exist.
            // If it does not exist, it is not yet created.
            FileInfo fi = new FileInfo("temp.txt");
            // Create a writer, ready to add entries to the file.
            StreamWriter sw = fi.AppendText();
            sw.WriteLine("Add as many lines as you like...");
            sw.WriteLine("Add another line to the output...");
            sw.Flush();
            sw.Close();
            // Get the information out of the file and display it.
            StreamReader sr = new StreamReader(fi.OpenRead());
            Console.WriteLine("This is the information in the first file:");
            while (sr.Peek() != -1)
                Console.WriteLine(sr.ReadLine());
            // Copy this file to another file. The file will not be overwritten if it already exists.
            FileInfo newfi = fi.CopyTo("newTemp.txt");
            // Get the information out of the new file and display it.
            sr = new StreamReader(newfi.OpenRead());
            Console.WriteLine("{0}This is the information in the second file:", Environment.NewLine);
            while (sr.Peek() != -1)
                Console.WriteLine(sr.ReadLine());
        }
        catch(Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }
}
//This code produces output similar to the following;
//results may vary based on the computer/file structure/etc.:
//
//This is the information in the first file:
//Add as many lines as you like...
//Add another line to the output...

//This is the information in the second file:
//Add as many lines as you like...
//Add another line to the output...
Imports System.IO

Public Class CopyToTest
    Public Shared Sub Main()
        Try
            ' Create a reference to a file, which might or might not exist.
            ' If it does not exist, it is not yet created.
            Dim fi As New FileInfo("temp.txt")
            ' Create a writer, ready to add entries to the file.
            Dim sw As StreamWriter = fi.AppendText()
            sw.WriteLine("Add as many lines as you like...")
            sw.WriteLine("Add another line to the output...")
            sw.Flush()
            sw.Close()
            ' Get the information out of the file and display it.
            Dim sr As New StreamReader(fi.OpenRead())
            Console.WriteLine("This is the information in the first file:")
            While sr.Peek() <> -1
                Console.WriteLine(sr.ReadLine())
            End While
            ' Copy this file to another file.
            Dim newfi As FileInfo = fi.CopyTo("newTemp.txt")
            ' Get the information out of the new file and display it.
            sr = New StreamReader(newfi.OpenRead())
            Console.WriteLine("{0}This is the information in the second file:", Environment.NewLine)
            While sr.Peek() <> -1
                Console.WriteLine(sr.ReadLine())
            End While
        Catch e As Exception
            Console.WriteLine(e.Message)
        End Try
    End Sub
End Class
'This code produces output similar to the following; 
'results may vary based on the computer/file structure/etc.:
'
'This is the information in the first file:
'Add as many lines as you like...
'Add another line to the output...
'
'This is the information in the second file:
'Add as many lines as you like...
'Add another line to the output...

Remarques

Utilisez la méthode pour autoriser le CopyTo(String, Boolean) remplacement d’un fichier existant.

Avertissement

Dans la mesure du possible, évitez d’utiliser des noms de fichiers courts (tels que XXXXXX~1.XXX) avec cette méthode. Si deux fichiers ont des noms de fichiers courts équivalents, cette méthode peut échouer et déclencher une exception et/ou entraîner un comportement indésirable

Voir aussi

S’applique à

CopyTo(String, Boolean)

Source:
FileInfo.cs
Source:
FileInfo.cs
Source:
FileInfo.cs
Source:
FileInfo.cs
Source:
FileInfo.cs

Copie un fichier existant dans un nouveau fichier, ce qui permet le remplacement d’un fichier existant.

public:
 System::IO::FileInfo ^ CopyTo(System::String ^ destFileName, bool overwrite);
public System.IO.FileInfo CopyTo(string destFileName, bool overwrite);
member this.CopyTo : string * bool -> System.IO.FileInfo
Public Function CopyTo (destFileName As String, overwrite As Boolean) As FileInfo

Paramètres

destFileName
String

Nom du nouveau fichier à copier.

overwrite
Boolean

true pour permettre à un fichier existant d’être remplacé ; sinon, false.

Retours

Un nouveau fichier, ou un remplacement d’un fichier existant, le cas overwrite échéant true. Si le fichier existe et overwrite est false, il IOException est levée.

Exceptions

.NET Framework et les versions .NET Core antérieures à la version 2.1 : destFileName est vide, contient uniquement des espaces blancs ou contient des caractères non valides.

Une erreur se produit ou le fichier de destination existe déjà et overwrite est false.

L’appelant n’a pas l’autorisation requise.

destFileName a la valeur null.

Le répertoire spécifié dans destFileName n’existe pas.

Un chemin d’accès au répertoire est transmis, ou le fichier est déplacé vers un autre lecteur.

Le chemin d’accès spécifié, le nom de fichier ou les deux dépassent la longueur maximale définie par le système.

destFileName contient un signe deux-points (:) au milieu de la chaîne.

Exemples

L’exemple suivant illustre les deux surcharges de la CopyTo méthode.

using System;
using System.IO;

class Test
{

    public static void Main()
    {
        string path = @"c:\SoureFile.txt";
        string path2 = @"c:\NewFile.txt";
        FileInfo fi1 = new FileInfo(path);
        FileInfo fi2 = new FileInfo(path2);

        try
        {
            // Create the source file.
            using (FileStream fs = fi1.Create()) { }

            //Ensure that the target file does not exist.
            if (File.Exists(path2))
            {
                fi2.Delete();
            }

            //Copy the file.f
            fi1.CopyTo(path2);
            Console.WriteLine("{0} was copied to {1}.", path, path2);
        }
        catch (IOException ioex)
        {
            Console.WriteLine(ioex.Message);
        }
    }
}
Imports System.IO

Public Class Test

    Public Shared Sub Main()
        'Specify the directories you want to manipulate.
        Dim path As String = "c:\SourceFile.txt"
        Dim path2 As String = "c:\NewFile.txt"
        Dim fi As FileInfo = New FileInfo(path)
        Dim fi2 As FileInfo = New FileInfo(path2)

        Try
            Using fs As FileStream = fi.Create()
            End Using

            'Ensure that the target does not exist.
            If File.Exists(path2) Then
                fi2.Delete()
            End If
            
            'Copy the file.
            fi.CopyTo(path2)
            Console.WriteLine("{0} was copied to {1}.", path, path2)

        Catch ioex As IOException
            Console.WriteLine(ioex.Message)
        End Try
    End Sub
End Class

L’exemple suivant illustre la copie d’un fichier dans un autre fichier, en spécifiant s’il faut remplacer un fichier qui existe déjà.

using System;
using System.IO;

public class CopyToTest
{
    public static void Main()
    {
        // Create a reference to a file, which might or might not exist.
        // If it does not exist, it is not yet created.
        FileInfo fi = new FileInfo("temp.txt");
        // Create a writer, ready to add entries to the file.
        StreamWriter sw = fi.AppendText();
        sw.WriteLine("Add as many lines as you like...");
        sw.WriteLine("Add another line to the output...");
        sw.Flush();
        sw.Close();
        // Get the information out of the file and display it.
        StreamReader sr = new StreamReader( fi.OpenRead() );
        Console.WriteLine("This is the information in the first file:");
        while (sr.Peek() != -1)
            Console.WriteLine( sr.ReadLine() );
        // Copy this file to another file. The true parameter specifies
        // that the file will be overwritten if it already exists.
        FileInfo newfi = fi.CopyTo("newTemp.txt", true);
        // Get the information out of the new file and display it.
        sr = new StreamReader( newfi.OpenRead() );
        Console.WriteLine("{0}This is the information in the second file:", Environment.NewLine);
        while (sr.Peek() != -1)
            Console.WriteLine( sr.ReadLine() );
    }
}
//This code produces output similar to the following;
//results may vary based on the computer/file structure/etc.:
//
//This is the information in the first file:
//Add as many lines as you like...
//Add another line to the output...
//Add as many lines as you like...
//Add another line to the output...

//This is the information in the second file:
//Add as many lines as you like...
//Add another line to the output...
//Add as many lines as you like...
//Add another line to the output...
Imports System.IO

Public Class CopyToTest
    Public Shared Sub Main()
        ' Create a reference to a file, which might or might not exist.
        ' If it does not exist, it is not yet created.
        Dim fi As New FileInfo("temp.txt")
        ' Create a writer, ready to add entries to the file.
        Dim sw As StreamWriter = fi.AppendText()
        sw.WriteLine("Add as many lines as you like...")
        sw.WriteLine("Add another line to the output...")
        sw.Flush()
        sw.Close()
        ' Get the information out of the file and display it.
        Dim sr As New StreamReader(fi.OpenRead())
        Console.WriteLine("This is the information in the first file:")
        While sr.Peek() <> -1
            Console.WriteLine(sr.ReadLine())
        End While
        ' Copy this file to another file. The true parameter specifies 
        ' that the file will be overwritten if it already exists.
        Dim newfi As FileInfo = fi.CopyTo("newTemp.txt", True)
        ' Get the information out of the new file and display it.
        sr = New StreamReader(newfi.OpenRead())
        Console.WriteLine("{0}This is the information in the second file:", Environment.NewLine)
        While sr.Peek() <> -1
            Console.WriteLine(sr.ReadLine())
        End While
    End Sub
End Class
'This code produces output similar to the following; 
'results may vary based on the computer/file structure/etc.:
'
'This is the information in the first file:
'Add as many lines as you like...
'Add another line to the output...
'
'This is the information in the second file:
'Add as many lines as you like...
'Add another line to the output...
'

Remarques

Utilisez cette méthode pour autoriser ou empêcher le remplacement d’un fichier existant. Utilisez la CopyTo(String) méthode pour empêcher le remplacement d’un fichier existant par défaut.

Avertissement

Dans la mesure du possible, évitez d’utiliser des noms de fichiers courts (tels que XXXXXX~1.XXX) avec cette méthode. Si deux fichiers ont des noms de fichiers courts équivalents, cette méthode peut échouer et déclencher une exception et/ou entraîner un comportement indésirable

Voir aussi

S’applique à