tags:

views:

1150

answers:

1

I have a document library in sharepoint. when a new file is uploaded to that library i want it to automatically get copied to a another document library as well. how can i do this?

+3  A: 

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();
    }
}

Deployment

You have various options for deployment as well. You can associate event receivers with a feature connected to a content type or list, and programmatically add them. See this article at SharePointDevWiki for more details.

Alex Angas
Make sure to not forget to copy metadata as well!!
Colin
Thanks, I've now added that!
Alex Angas
Hi Alex, i noticedd a CopyTo method associated with the SPFile object. can I make use of this?
raklos
@raklos Answer now updated, good find! Thanks
Alex Angas