Export (0) Print
Expand All

FileInfo.CopyTo Method

Copies an existing file to a new file.

Overload List

Copies an existing file to a new file, disallowing the overwriting of an existing file.

Supported by the .NET Compact Framework.

[Visual Basic] Overloads Public Function CopyTo(String) As FileInfo
[C#] public FileInfo CopyTo(string);
[C++] public: FileInfo* CopyTo(String*);
[JScript] public function CopyTo(String) : FileInfo;

Copies an existing file to a new file, allowing the overwriting of an existing file.

Supported by the .NET Compact Framework.

[Visual Basic] Overloads Public Function CopyTo(String, Boolean) As FileInfo
[C#] public FileInfo CopyTo(string, bool);
[C++] public: FileInfo* CopyTo(String*, bool);
[JScript] public function CopyTo(String, Boolean) : FileInfo;

Example

[Visual Basic, C#, C++] The following example demonstrates both overloads of the CopyTo method.

[Visual Basic, C#, C++] Note   This example shows how to use one of the overloaded versions of CopyTo. For other examples that might be available, see the individual overload topics.
[Visual Basic] 
Imports System
Imports System.IO

Public Class Test

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

        Try
            Dim fs As FileStream = fi.Create()
            fs.Close()
            'Ensure that the target does not exist.
            fi2.Delete()
            'Copy the file.
            fi.CopyTo(path2)
            Console.WriteLine("{0} was copied to {1}.", path, path2)
            'Try to copy it again, which should succeed.
            fi.CopyTo(path2, True)
            Console.WriteLine("The second Copy operation succeeded, which is expected.")

        Catch
            Console.WriteLine("Double copying was not allowed, which is not expected.")
        End Try
    End Sub
End Class

[C#] 
using System;
using System.IO;

class Test 
{
    
    public static void Main() 
    {
        string path = @"c:\temp\MyTest.txt";
        string path2 = @"c:\temp\MyTest.txt" + "temp";
        FileInfo fi1 = new FileInfo(path);
        FileInfo fi2 = new FileInfo(path2);

        try 
        {
            // Create the file and clean up handles.
            using (FileStream fs = fi1.Create()) {}

            //Ensure that the target does not exist.
            fi2.Delete();

            //Copy the file.
            fi1.CopyTo(path2);
            Console.WriteLine("{0} was copied to {1}.", path, path2);

            //Try to copy it again, which should succeed.
            fi1.CopyTo(path2, true);

            Console.WriteLine("The second Copy operation succeeded, which is expected.");

        } 
        catch 
        {
            Console.WriteLine("Double copying was not allowed, which is not expected.");
        }
    }
}

[C++] 
#using <mscorlib.dll>

using namespace System;
using namespace System::IO;

int main() {
    String* path = S"c:\\temp\\MyTest.txt";
    String* path2 = S"c:\\temp\\MyTest.txttemp";
    FileInfo* fi1 = new FileInfo(path);
    FileInfo* fi2 = new FileInfo(path2);

    try {
        // Create the file and clean up handles.
        FileStream* fs = fi1->Create();
        if (fs) __try_cast<IDisposable*>(fs)->Dispose();

        //Ensure that the target does not exist.
        fi2->Delete();

        //Copy the file.
        fi1->CopyTo(path2);
        Console::WriteLine(S"{0} was copied to {1}.", path, path2);

        //Try to copy it again, which should succeed.
        fi1->CopyTo(path2, true);

        Console::WriteLine(S"The second Copy operation succeeded, which is expected.");
    } catch (Exception*) {
        Console::WriteLine(S"Double copying was not allowed, which is not expected.");
    }
}

[Visual Basic, C#, C++] The following example demonstrates copying one file to another file, specifying whether to overwrite a file that already exists.

[Visual Basic] 
Imports System
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 'Main
End Class 'CopyToTest

[C#] 
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() );
    }
}

[C++] 
#using <mscorlib.dll>

using namespace System;
using namespace System::IO;

int 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(S"temp.txt");
    // Create a writer, ready to add entries to the file.
    StreamWriter* sw = fi->AppendText();
    sw->WriteLine(S"Add as many lines as you like...");
    sw->WriteLine(S"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(S"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(S"newTemp.txt", true);
    // Get the information out of the new file and display it.* sr = new StreamReader( newfi->OpenRead() );
    Console::WriteLine(S"{0}This is the information in the second file:", Environment::NewLine);
    while (sr->Peek() != -1)
        Console::WriteLine(sr->ReadLine());
}

[JScript] No example is available for JScript. To view a Visual Basic, C#, or C++ example, click the Language Filter button Language Filter in the upper-left corner of the page.

See Also

FileInfo Class | FileInfo Members | System.IO Namespace

Show:
© 2014 Microsoft