Click here to Skip to main content
14,304,321 members

Sharepoint WebPart for Programmatically Uploading Files to the Shared Documents Library

Rate this:
4.00 (1 vote)
Please Sign up or sign in to vote.
4.00 (1 vote)
22 Jul 2010CPOL
This article describes the step by step processes to create a Web Part using C# for SharePoint Server 2007, and to programmatically upload a collection of files to the Document Library in SharePoint Server 2007.


This article describes the step by step processes to create a Web Part using C# for SharePoint Server 2007, and to programmatically upload a collection of files to the Document Library in SharePoint Server 2007.

“Document Libraries, also called shared documents, are collections of files that can be shared with team members on Web based Microsoft Windows SharePoint Services”. By default, your team website comes with a built-in document library named Shared Documents, which is listed on the quick launch bar as well as on the Documents and Lists page. As shown below:

Image 1

The files in Shared Documents are accessible for users who have permissions to read.


It is required that the set of files present in a local or network computer need to be programmatically uploaded to the Shared Documents library of a SharePoint site by anyone who can access it from any part of the world. This can be done by creating a Share Point WebPart in Visual Studio .NET 2005 using C#. The steps to create a Web Part are:

  • Start VS.NET 2005 and create a new project (Class Library).
  • Rename the class as WebpartUploadFiles.
  • Add the following references by right clicking on the WebpartUploadFiles project and clicking on “Add Reference”: Microsoft.SharePoint and Microsoft.SharePoint.WebControls.
  • Note: If SharePoint Server 2007 is not installed on the local machine, then copy Microsoft.SharePoint.dll from the folder where it is installed to a folder on the computer where you will be developing the Web Parts.

  • Use the Render method: The Webpart base class seals the Render method of System.Web.UI.Control because the Web Part infrastructure needs to control rendering the contents of a Web Part. For this reason, custom Web Parts must override the Render method of the Webpart base class. Create a UploadFiles() method.
  • //The Complete Web part Code :
    #region File Information
    ///<span class="code-SummaryComment"><summary>
    </span>/// ----------------------------------------------------------------------
    /// Namespace : WebpartUploadFiles
    /// Purpose   : To Create Webpart to programmatically upload Files
    //              to DocumentLibrary
    /// Change History
    /// ----------------------------------------------------------------------
    /// Date            Edit            Author            Comment              
    /// -------------+--------+-----------------------------------------------
    /// 08-Jan-2007    [100]          Rajesh_Sajjanar     Create Webpart
    /// -------------+--------+-----------------------------------------------
    ///<span class="code-SummaryComment"></summary>
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Drawing;                    //For Color
    using Microsoft.SharePoint;              // For all sharepoint related API’s
    using Microsoft.SharePoint.WebControls;  //For sharepoint webpage Controls
    using System.Web.UI.WebControls;         //For System.Web.UI.WebControls; 
    using System.IO;                         //For File Handling
    namespace WebpartUploadFiles
        //Inherits the Webparts class
        public class WebpartUploadFiles : 
            #region Decalration
            private Label lblResults;
            FileInfo[] Finfo;
            SPSite objSite;
            SPWeb objWeb;
            /* The WebPart base class seals the Render method of System.Web.UI.Control 
            because the Web Part infrastructure needs to control rendering the contents 
            of a Web Part for this reason, custom Web Parts must override 
            the Render method of the WebPart base class  */
            protected override void Render(System.Web.UI.HtmlTextWriter writer)
           //Ovveride the method to create the objects for the Web Part's controls.
            protected override void CreateChildControls()
    #region Method For UpLoadFiles
            private void UploadFiles()
                    DirectoryInfo Dinfo = new DirectoryInfo(@"\\BLRRCS\Reports");         
                    // BLRRCS -path from where the file  eeds to be uploaded
                    Finfo = Dinfo.GetFiles("*.*");
                    //Can be set to *.pdf , *.txt ,*.doc etc
                    this.lblResults = new Label();
                    objSite = SPControl.GetContextSite(Context);
                    objWeb = objSite.OpenWeb();
                    objWeb.AllowUnsafeUpdates = true;
                    SPList objList = objWeb.Lists["Shared Documents"];
                    SPDocumentLibrary objLib = null;
                    objLib = (SPDocumentLibrary)objList;
                    SPFolder rFolder = objLib.RootFolder;
                    SPFile objFile = null;
                    byte[] byteArr = null;
                  foreach (FileInfo f in Finfo)
                    byteArr = 
                      File.ReadAllBytes(@"\\BLRRCS\Reports\" + f.Name + " ");
                    objFile = rFolder.Files.Add(rFolder.Url + "/" + 
                                                f.Name + "", byteArr, true);
                    lblResults.Text = 
                      "Files are Uploaded  to Shared Document Library"
                    lblResults.Font.Bold = true;
                    this.lblResults.ForeColor = System.Drawing.Color.Blue;
                catch (SPException s)
  • Build the project to get WebpartUploadFiles.dll.
  • Deploying the Web Part to SharePoint: Now we need to deploy the Web Part in the SharePoint Server. To let SharePoint know that the assembly is safe, we have to add it to the safe control list in the web.config of the SharePoint web. We need the public key token from the DLL for this. For this, follow the step mentioned below.
  • Build the project. Once built successfully, go to Properties by right clicking the WebpartUploadFiles project and clicking on Properties. Open the project properties and go to the ‘Signing’ section. Create a new key and build the project. A Strong Key is created in the project as shown:
  • Image 2

  • Now drag and drop the following compiled assembly into the GAC (by default, c:\windows\assembly). As shown below:
  • Image 3

  • Open the properties of the DLL to get the public key token by right clicking on WebpartUploadFiles in the GAC.
  • Image 4

    Image 5

  • Now register the assembly as a safe control in web.config.
  • <SafeControl 
      Assembly="WebpartUploadFiles, Version=, 
                Culture=neutral, PublicKeyToken=bb6a94ca67a100c4" 
      Namespace="WebpartUploadFiles" TypeName="*" Safe="True" />

    Note: Now go to the command prompt and do RESETIIS (restart IIS server).

  • In SharePoint 2007 Server, once a WebpartUploadFiles.dll is registered in the web.config, SharePoint can automatically detect the WebPart from those DLLs. With the site settings page, we can now automatically populate the WebPart gallery. In SharePoint, go to he HOME site and click 'Site Actions' -> 'Site Settings' -> and, then under ‘Modify All Site Settings’:
  • Image 6

  • Under ‘Galleries’, click ‘Web Parts’. Then click ‘New’.
  • Image 7

  • Now, the new WebPart(s) will appear in the list. If not, try an IISRESET and refresh the page.
  • Image 8

  • Click on New.
  • Image 9

  • Select the WebPart as shown below:
  • Image 10

  • Click on Populate Gallery.
  • Image 11

  • Now, we can go to the page in SharePoint where you want to add the WebPart. On the SharePoint site, click ‘Site Actions’ -> ‘Edit Page’ -> click on ‘Add a WebPart’ -> select the WebPart to add, and click ‘Add’.
  • Image 12

    Image 13

  • The WebPart is added on the page where the CreateChildControls() method is called. The WebPart WebpartUploadFiles executes immediately, and displays a message saying "Document is created and Uploaded to RCS Library", as shown below:
  • Image 14

  • Each time you click on the Shared Documents link, the WebPart executes and all files present in the path \\BLRRCS\Reports\ which is mentioned in the code get uploaded to the Shared Documents library.
  • Image 15

Improvements to the Web Part

  1. The path mentioned in the code can also be read from an XML file, and then it can be made flexible to use any local computer path.
  2. The Web Part works only for the local folder path and uploads all the files present in the local computer folder path.
  3. If network files need to be uploaded, then create a batch file as shown below and add the batch file to a Windows scheduled task. Enter the Copy command in Notepad, as shown below, and save it as a .Bat file.

    COPY "Network file path" "Local Computer Folder path"

    Image 16

    Add the Run.Bat file to a Windows Schedule Task (a Windows Service can also be used), and set the day, time interval when to run the batch file.

    Whenever the Windows scheduled task runs this Run.Bat, the files get transferred from the network path \\BLRRCS\Report to the local computer path C:\UploadFiles., thus making network files available locally, and whenever the Share Point Server Shared Documents library menu is clicked, the files will be automatically uploaded to the Shared Documents library.

  4. The file formats can be set to *.PDF ,*.doc , *.txt etc …
  5. The below screen shows the uploaded files to the Shared Documents library in SharePoint Server.

    Image 17

I hope the content presented in this article is useful. For any queries, please drop a mail at


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Rajesh Sajjanar
Architect MNC
India India
Rajesh Sajjanar is Technical Lead working for Enterprise Dotnet applications in Bangalore, INDIA. He holds batchelor degree in Electronics and Communication Engineering from Visvesvaraya Technological University Belgaum INDIA

Comments and Discussions

Questionhow to add files to document library in folder wise using visual webpart Pin
Member 917679425-Jan-13 0:16
memberMember 917679425-Jan-13 0:16 
QuestionQuery???? Pin
venkatesun19-Nov-12 19:50
membervenkatesun19-Nov-12 19:50 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Posted 22 Jul 2010


7 bookmarked