SharePoint 2010: How to Copy Documents Between Sites in 2007 or 2010
I received a request from a site administrator to provide a way to copy documents between SharePoint sites. The requirement was to copy files between different site collections as well as sites created in other web applications. This tool should be executed in two modes:
- the first mode it will copy all files from the source folder to the destination folder
- the second mode should copy the specific file from the source folder to the destination folder. This folder can be a document library or a folder inside the document library.
This will also check in the file so that it will be visible to authorized users. If the file already exists in the destination location this tool will overwrite the file. I have tested this in both SharePoint 2007 and SharePoint 2010.
I am sharing the code below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
namespace CopyDocumentLibrariesRashu
{
class Program
{
static void Main(string[] args)
{
try
{
Console.WriteLine("Hello, This tool will copy the the files between the folders specified. It will overwrite the file if it exists at the destination location");
Console.WriteLine("Please enter the URL of the source folder");
string sourceURL = Console.ReadLine();
Console.WriteLine("Please enter the URL of the destination folder");
string destinationURL = Console.ReadLine();
Console.WriteLine("do you want to copy a specific file?if yes then type y or else type anything else");
String fileDecision = Console.ReadLine();
String cFile = string.Empty;
if(fileDecision == "y")
{
Console.WriteLine("Please enter the filename with extension of the file");
cFile = Console.ReadLine();
}
using (SPSite sourceSite = new SPSite(sourceURL))
{
using (SPWeb sourceWeb = sourceSite.OpenWeb())
{
using (SPSite destinationSite = new SPSite(destinationURL))
{
using (SPWeb destinationWeb = destinationSite.OpenWeb())
{
SPFolder sList = (SPFolder)sourceWeb.GetFolder(sourceURL);
SPFolder dList = (SPFolder)destinationWeb.GetFolder(destinationURL);
SPList dLibrary = destinationWeb.Lists[dList.ContainingDocumentLibrary];
SPFileCollection files = sList.Files;
if (fileDecision != "y")
{
foreach (SPFile ctFile in files)
{
byte[] sbytes = ctFile.OpenBinary();
SPFile dFileName = dList.Files.Add(ctFile.Name, sbytes, true);
if (dFileName.CheckOutStatus != SPFile.SPCheckOutStatus.None)
{
dFileName.CheckIn("Checking in");
}
}
}
else
{
SPFile desFile = sList.Files[sourceURL +"/" + cFile];
byte[] sbytes = desFile.OpenBinary();
SPFile dFileName = dList.Files.Add(desFile.Name, sbytes, true);
if (dFileName.CheckOutStatus != SPFile.SPCheckOutStatus.None)
{
dFileName.CheckIn("Checking in");
}
}
destinationWeb.Update();
Console.WriteLine("The operation completed successfully");
Console.ReadLine();
}
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}