2009-06-29 52 views
10

我在SharePoint中有一個文檔庫。當新文件上傳到該庫時,我希望它自動複製到另一個文檔庫。我怎樣才能做到這一點?將文件複製到SharePoint中的文檔庫中

+0

在C#和SharePoint標記的上下文中,這個問題非常有意義 - 投票重新打開。 – 2015-09-01 22:09:31

回答

14

使用項目事件接收器並覆蓋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); 
    } 
} 

方法2:流拷貝,手動設置屬性

,如果你需要在哪個項目屬性複製或如果文件內容需要修改更多的控制這種方法就只能是必要的。

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

部署

您有部署的各種選項,以及。您可以將事件接收器與連接到內容類型或列表的功能相關聯,並以編程方式添加它們。有關更多詳細信息,請參閱this article at SharePointDevWiki

+0

請務必不要忘記複製元數據! – Colin 2009-06-29 17:04:06

相關問題