Export (0) Print
Expand All

SPFile.CopyTo method (String)

Copies the file to the destination URL but does not overwrite an existing file of the same name.

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

public void CopyTo(
	string strNewUrl
)

Parameters

strNewUrl
Type: System.String

The destination URL.

ExceptionCondition
SPException

An error occurred while copying the file.

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

This method returns an error if a file of the same name already exists at the new location. To copy a file and overwrite an existing file, call CopyTo(String, Boolean) with strNewUrl and true.

The following code example copies files from one document library into another if the files are checked into the original library with the comment "Complete".

SPSite oSiteCollection = SPContext.Current.Site;
using(SPWeb oWebsite = oSiteCollection.AllWebs["Site_Name"])
{
    SPFileCollection collFiles =   
        oWebsite.GetFolder("Source_DocLibrary").Files;

    for (int intIndex=0; i<collFiles.Count; intIndex++)
    {
        if (collFiles[intIndex].CheckInComment == "Complete")
        {
            colFiles[intIndex].CopyTo("Destination_DocLibrary/" + 
                colFiles[intIndex].Name);
        }
    }
}
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