Visual Studio workflow: Copy a document from one SharePoint document library to another
Learn how you can create a Visual Studio workflow to copy a document from one SharePoint document library to another on the same or a different site.
This article demonstrates how you can create a Visual Studio workflow that can be manually started on a document in a SharePoint document library to copy that document to another document library on the same or another SharePoint site.
Creating the custom SharePoint workflow
- In SharePoint, create 2 document libraries: One to copy documents from and another one to store the copied documents in. Note: These document libraries do not have to be located on the same site.
- In Visual Studio, create a SharePoint Sequential Workflow. If you are unsure as to which steps you have to take to create a SharePoint workflow, refer to the tutorials in the Visual Studio workflows for SharePoint mini course.
- Add a Code activity to the workflow.
Figure 1. SharePoint Sequential Workflow with a code activity to copy a document to a library.
Write the following code in the ExecuteCode event handler of the Code activity:
// Get the item the workflow is running on
SPListItem item = workflowProperties.Item;
// Set the name of the document library and site
// where to copy the document to
string siteUrl = "http://<ServerName>/<SiteName>/";
string libName = "DocLibForCopies";
// Open the site
using (SPSite site = new SPSite(siteUrl))
using (SPWeb web = site.OpenWeb())
if (item.File != null)
// Copy the document to the library
SPFolder library = web.Folders[libName];
where ServerName is the name of your SharePoint server, SiteName the name of the site on which the second document library is located, and DocLibForCopes the name of the second document library to which documents will be copied.
- Attach the workflow to the document library that contains the documents you want to copy, and select the Allow this workflow to be manually started by an authenticated user with Edit Item Permissions check box when attaching the workflow to the document library.
Testing the workflow
Now whenever you manually start the workflow on a document in the first document library, that document will be copied to the second document library and the workflow will end.
To manually start the workflow:
- Hover over a document in the first document library until a drop-down list box appears, click on the down arrow, and select Workflows from the context menu that appears.
Figure 2. Accessing the workflows that can run on a document in a SharePoint document library.
- On the Workflows page under Start a New Workflow, click the workflow you want to start.
Figure 3. Manually starting a SharePoint workflow.
- 3 Ways to create workflows for WSS 3.0 and Office SharePoint 2007
- How to create custom Visual Studio 2005 workflows for WSS 3 or Office SharePoint Server 2007
- How to enable a Visual Studio workflow on SharePoint and attach it to a document library