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?
This behavior is by design. You can't drag folders into document libraries by using a web browser. This feature is limited to files. If you try to drag a folder into a document library, you'll receive an error message.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With