Sharepoint 2013 Event handler for document library

Hi,

need ItemAdded event handler

to move or copy document in document library to another document library of other sharepoint farm.

How to achieve this.

Thanks,

Siva.

May 15th, 2015 9:07pm

Hi

Use an item event receiver and override the ItemAdded event. SPItemEventProperties will give you a reference to the list item via the ListItem property.

There are two methods to do this (thanks to your discovery of CopyTo).

                                                                               

Method 1: Use CopyTo

This method copies any list item with its associated file and properties to any location in the same site collection (possibly other web applications as well but I haven't tested). SharePoint automatically maintains the link to the source item as well if you view the item's properties or use its drop-down menu. This link can be removed with UnlinkFromCopySource.

The only trick to CopyTo is that a full URL is required for the destination location.

public class EventReceiverTest : SPItemEventReceiver
{
    public override void ItemAdded(SPItemEventProperties properties)
    {properties.ListItem.CopyTo(properties.WebUrl + "/Destination/" + properties.ListItem.File.Name);
    }
}


Method 2: Stream copy, manually set properties

This method would only be necessary if you need more control over which item properties are copied or if the file's contents need to be altered.

                                                                       

public class EventReceiverTest : SPItemEventReceiver
{
    public override void ItemAdded(SPItemEventProperties properties)
    {
SPFile sourceFile = properties.ListItem.File;
SPFile destFile;

// Copy file from source library to destination
using (Stream stream = sourceFile.OpenBinaryStream())
{
SPDocumentLibrary destLib =
(SPDocumentLibrary) properties.ListItem.Web.Lists["Destination"];
destFile = destLib.RootFolder.Files.Add(sourceFile.Name, stream);
stream.Close();
}

// Update item properties
SPListItem destItem = destFile.Item;
SPListItem sourceItem = sourceFile.Item;
destItem["Title"] = sourceItem["Title"];
//...
//... destItem["FieldX"] = sourceItem["FieldX"];
//...
destItem.UpdateOverwriteVersion();
    }
}

http://stackoverflow.com/questions/1059175/copy-files-to-document-library-in-sharepoi

May 16th, 2015 1:54am

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics