Sunday, October 07, 2012

SharePoint 2010 - Programmatically Copy Picture to Image Library on Item Added

SharePoint 2010 - Pro grammatically Copy Picture to Image Library on Item Added
Scenario:
Two Picture Libraries
PicLib and PicLib2

Requirement:
When an image is uploaded by user in First Picture Library upload the same image in PicLib2.
Solution
Create a new Project in VS 2010 (Event Receiver Project)
Select the site where you want to deploy this
Select the source List (PicLib in our scenario) and ItemAdded event
Write Code below in ItemAdded

public override void ItemAdded(SPItemEventProperties properties)
{
base.ItemAdded(properties);

try
{
SPList lib1 = (SPDocumentLibrary) properties.Web.Lists ["piclib"];
SPList lib2 = (SPDocumentLibrary)properties.Web.Lists["piclib2"];
SPListItem item1 = properties.ListItem;
byte[] fileBytes = item1.File.OpenBinary();
string destinationUrl = lib2.RootFolder.Url + "/" + item1.File.Name;
SPFile destFile = lib2.RootFolder.Files.Add(destinationUrl , fileBytes, true);

}
catch (Exception e)
{
throw e;
}
}