SharePoint 2010 Document Library Replicator: Part 1

I have been recently working on coding a SharePoint document library replicator. Everytime an item is updated in one library, I wanted to ensure a copy of the updated document is written to another library within the same Web.

Even though I am still working in the final solution, I wanted to share a small code snippet which is a SharePoint 2010 Event Receiver that copies a file from one library to a specified target document library named “targetlibrary”. To perform this basic function the code was very straight forward, and any libraries that get updated would get the file copied to the target library within the Web.

The properties are hard-coded in this sample, but in my final solution I may have a list which manages source and destination library urls. It could also handle and manage SPFolders from the source to the target libraries. I’m also adding a log writer to show the copied files with a timestamp that shows properties such as the last user who edited the file. The log writer will write the information to a SharePoint list.

*** You may want to add some code to skip the block if an update is made to the target library ***

using System;

using System.Security.Permissions;

using Microsoft.SharePoint;

using Microsoft.SharePoint.Security;

using Microsoft.SharePoint.Utilities;

using Microsoft.SharePoint.Workflow;

using System.IO;

namespace DocLibraryReplicator.Document_Library_Receiver

{

///<summary>

/// List Item Events///</summary>

publicclass Document_Library_Receiver : SPItemEventReceiver

{

///<summary>/// An item was added.///</summary>

publicoverridevoid ItemAdded(SPItemEventProperties properties)

{

base.ItemAdded(properties);

}

///<summary>/// An item was updated.///</summary>

publicoverridevoid ItemUpdated(SPItemEventProperties properties)

{

base.ItemUpdated(properties);

using (SPSite spsite = newSPSite(properties.WebUrl))

try

{

// determine target filename – the same as the source

string targefilename = properties.ListItem.Name.ToString();

// Disable Event Firing as the target will try to copy to itself

EventFiringEnabled = false;

 // Copy the file to the destination library (targetlibrary) ** BEWARE ** Target file overwritten with true directive

properties.ListItem.File.CopyTo(properties.WebUrl + “/” + “targetlibrary” + “/” + targefilename, true);

 // Enable Event Firing

EventFiringEnabled = true;

}

catch (SPException spEx) { }

finally { }

}

}

}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: