SPFile.CopyTo method (String, Boolean)

Copies the file to the destination URL and optionally overwrites an existing file of the same name.

Namespace:  Microsoft.SharePoint
Assembly:  Microsoft.SharePoint (in Microsoft.SharePoint.dll)


Public Sub CopyTo ( _
    strNewUrl As String, _
    bOverWrite As Boolean _
Dim instance As SPFile
Dim strNewUrl As String
Dim bOverWrite As Boolean

instance.CopyTo(strNewUrl, bOverWrite)
public void CopyTo(
    string strNewUrl,
    bool bOverWrite


  • strNewUrl
    Type: System.String

    The destination URL of the new file.

  • bOverWrite
    Type: System.Boolean

    true to overwrite an existing file of the same name; otherwise false.


Exception Condition

An error occurred while copying the file.


The CopyTo method copies files to another location on the same site. To copy files to a location in another site, use one of the Add methods of the SPFileCollection class.

This method returns an error if bOverWrite is set to false and a file of the same name already exists at the new location.


The following code example copies all the files in the Shared Documents document library to another folder on the same site, overwriting any file of the same name.

Dim site As SPSite = SPContext.Current.Site
Dim web As SPWeb = site.AllWebs("Site_Name/Subsite_Name")
Dim files As SPFileCollection = web.GetFolder("Shared Documents").Files
Dim intIndex As Integer

For intIndex = 0 To files.Count - 1

    files(intIndex).CopyTo("Destination_DocLib/" & 
        files(intIndex).Name, True)

Next intIndex
SPSite oSiteCollection = SPContext.Current.Site;
using(SPWeb oWebsite = oSite.AllWebs["Site_Name/Subsite_Name"])
    SPFileCollection collFiles = oWebsite.GetFolder("Shared 

    for (int intIndex=0; intIndex<collFiles.Count; intIndex++)
        collFiles[intIndex].CopyTo("Destination_DocLib/" + 
            collFiles[intIndex].Name, true);


Certain objects implement the IDisposable interface, and you must avoid retaining these objects in memory after they are no longer needed. For information about good coding practices, see Disposing Objects.

See also


SPFile class

SPFile members

CopyTo overload

Microsoft.SharePoint namespace