Export (0) Print
Expand All

File.Copy Method (String, String, Boolean)

.NET Framework 1.1

Copies an existing file to a new file. Overwriting a file of the same name is allowed.

[Visual Basic]
Overloads Public Shared Sub Copy( _
   ByVal sourceFileName As String, _
   ByVal destFileName As String, _
   ByVal overwrite As Boolean _
)
[C#]
public static void Copy(
 string sourceFileName,
 string destFileName,
 bool overwrite
);
[C++]
public: static void Copy(
 String* sourceFileName,
 String* destFileName,
 bool overwrite
);
[JScript]
public static function Copy(
   sourceFileName : String,
 destFileName : String,
 overwrite : Boolean
);

Parameters

sourceFileName
The file to copy.
destFileName
The name of the destination file. This cannot be a directory.
overwrite
true if the destination file can be overwritten; otherwise, false.

Exceptions

Exception Type Condition
UnauthorizedAccessException The caller does not have the required permission.
ArgumentException sourceFileName or destFileName is a zero-length string, contains only white space, or contains one or more invalid characters as defined by InvalidPathChars.

-or-

sourceFileName or destFileName specifies a directory.

ArgumentNullException sourceFileName or destFileName is a null reference (Nothing in Visual Basic).
PathTooLongException The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.
DirectoryNotFoundException The path specified in sourceFileName or destFileName is invalid, such as being on an unmapped drive.
FileNotFoundException sourceFileName was not found.
IOException destFileName is read-only, or destFileName exists and overwrite is false.

-or-

An I/O error has occurred.

NotSupportedException sourceFileName or destFileName is in an invalid format.

Remarks

The sourceFileName and destFileName arguments are permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory.

For an example of using this method, see the Example section below. The following table lists examples of other typical or related I/O tasks.

To do this... See the example in this topic...
Create a text file. Writing Text to a File
Write to a text file. Writing Text to a File
Read from a text file. Reading Text from a File
Append text to a file. Opening and Appending to a Log File

File.AppendText

FileInfo.AppendText

Rename or move a file. File.Move

FileInfo.MoveTo

Delete a file. File.Delete

FileInfo.Delete

Read from a binary file. Reading and Writing to a Newly Created Data File
Write to a binary file. Reading and Writing to a Newly Created Data File
Move a directory. Directory.Move

DirectoryInfo.MoveTo

Create a subdirectory. CreateSubdirectory
Copy a directory. Directory

Example

[Visual Basic, C#, C++] The following example copies a file to the specified path, allowing the overwriting of a target file of the same name.

[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"

        Try
            Dim fs As FileStream = File.Create(path)
            fs.Close()

            ' Ensure that the target does not exist.
            File.Delete(path2)

            ' Copy the file.
            File.Copy(path, path2)
            Console.WriteLine("{0} copied to {1}", path, path2)

            ' Try to copy the same file again, which should succeed.
            File.Copy(path, path2, True)
            Console.WriteLine("The second Copy operation succeeded, which was expected.")

        Catch
            Console.WriteLine("Double copying is not allowed, which was 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 = path + "temp";

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

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

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

            // Try to copy the same file again, which should succeed.
            File.Copy(path, path2, true);
            Console.WriteLine("The second Copy operation succeeded, which was expected.");
        } 

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

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

using namespace System;
using namespace System::IO;

int main() {
    String* path = S"c:\\temp\\MyTest.txt";
    String* path2 = String::Concat(path, S"temp");

    try {
        // Create the file and clean up handles.
        IDisposable* file = __try_cast<IDisposable*>(File::Create(path));
        if (file) file->Dispose();

        // Ensure that the target does not exist.
        File::Delete(path2);

        // Copy the file.
        File::Copy(path, path2);
        Console::WriteLine(S"{0} copied to {1}", path, path2);

        // Try to copy the same file again, which should succeed.
        File::Copy(path, path2, true);
        Console::WriteLine(S"The second Copy operation succeeded, which was expected.");
    } catch (Exception*) {
        Console::WriteLine(S"Double copy is not allowed, which was not expected.");
    }
}

[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.

Requirements

Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family, .NET Compact Framework, Common Language Infrastructure (CLI) Standard

.NET Framework Security: 

See Also

File Class | File Members | System.IO Namespace | File.Copy Overload List | Working with I/O | Reading Text from a File | Writing Text to a File | Basic File I/O | Reading and Writing to a Newly Created Data File

Show:
© 2015 Microsoft