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)
Available in Sandboxed Solutions: Yes
Available in SharePoint Online
Syntax
'Declaration
Public Sub CopyTo ( _
strNewUrl As String _
)
'Usage
Dim instance As SPFile
Dim strNewUrl As String
instance.CopyTo(strNewUrl)
public void CopyTo(
string strNewUrl
)
Parameters
strNewUrl
Type: System.StringThe destination URL.
Exceptions
Exception | Condition |
---|---|
SPException | An error occurred while copying the file. |
Remarks
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.
Examples
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".
Dim site As SPSite = SPContext.Current.Site
Dim web As SPWeb = site.AllWebs("Site_Name")
Dim files As SPFileCollection =
web.GetFolder("Source_DocLibrary").Files
Dim intIndex As Integer
For intIndex = 0 To files.Count - 1
If files(intIndex).CheckInComment = "Complete" Then
files(intIndex).CopyTo("Destination_DocLibrary/" &
files(intIndex).Name)
End If
Next intIndex
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);
}
}
}
Note
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.