Export (0) Print
Expand All

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 void CopyTo(
	string strNewUrl,
	bool bOverWrite
)

Parameters

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.

ExceptionCondition
SPException

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.

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

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

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.

Show:
© 2014 Microsoft