将文件复制到SharePoint文档库

10

我在SharePoint中有一个文档库。当新文件上传到该库时,我希望它能自动复制到另一个文档库中。我该如何实现这个功能?


在C#和SharePoint标签的背景下,这个问题非常合理 - 投票重新开放。 - David Clarke
1个回答

15

使用项事件接收器并重写 ItemAdded 事件。通过 SPItemEventProperties 可以通过 ListItem 属性引用列表项。

有两种方法可以做到这一点(感谢您发现了 CopyTo)。

方法1:使用CopyTo

此方法将任何带有其关联文件和属性的列表项复制到同一站点集合中的任何位置(可能也包括其他 Web 应用程序,但我没有测试过)。如果查看该项的属性或使用其下拉菜单,则 SharePoint 还会自动维护到源项的链接。可以使用 UnlinkFromCopySource 删除此链接。

CopyTo 的唯一技巧是目标位置需要提供完整的 URL。

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

方法二:流复制,手动设置属性

只有在需要更多控制哪些项目属性需要被复制或者文件内容需要被改变的情况下,才需要使用此方法。

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

部署

你有多种部署选项。你可以将事件接收器与一个连接到内容类型或列表的特性相关联,并以编程方式添加它们。有关更多详细信息,请参见此文在SharePointDevWiki上的文章


一定要记得复制元数据!! - Colin
嗨,Alex,我注意到SPFile对象关联了一个CopyTo方法。我可以使用它吗? - raklos
@raklos 答案已更新,不错的发现!谢谢。 - Alex Angas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接