Sunday, December 27, 2009

Code to copy a file from one SP site to another.

This code can be used to copy a file from a source SharePoint site location to any other site within the same SharePoint server.

Code written in C# :

SPSite site = new SPSite("http://SPServer");
SPWeb web = site.RootWeb;
SPFile myFile = web.GetFile("http://SPServer/folder1/testdoc.docx");

// Read the contents of the file into a byte array.
byte[] sfile = myFile.OpenBinary();

//Get the destination server info.
SPSite site2 = new SPSite("http://SPServer2");
SPWeb web2 = site2.RootWeb;
SPFolderCollection testfolders = web2.Folders;

//New file in the name of newdoc.docx will be created in SPServer2/destfolder
//this file will contain the similar contents as testdoc.docx
SPFile testfile = testfolders["destfolder"].Files.Add("newdoc.docx", sfile);
testfile.Update();

No comments:

Post a Comment