Skip to content
Menu
SharePoint Gems
  • Power Platform
  • Development
    • SharePoint 2013
  • Migration
  • Administration
  • SP Online
  • Contact
  • About
    • Privacy Policy
SharePoint Gems
upload file to sharePoint Library Programmatically

Programmatically Upload a File in SharePoint Document Library.

Posted on March 10, 2020September 29, 2021
Programmatically upload files to document library in SharePoint

Hello ShareaPointers,

Today, In this article we will learn about How to upload a File into SharePoint Document Library using C# Code or how to Programmatically Upload a File in SharePoint Document Library.

We implemented this solution long back ago because our client requires to automate bulk upload documents. Hope in the latest technology changing world you will find this article helpful.

Please Note: This solution or Piece of code only applies to SharePoint On-premises versions Like MOSS 2007, SharePoint 2010, and SharePoint 2013.

Contents hide
1 Requirement:
1.1 Assumptions:
2 C# Program to upload the file into SharePoint Document Library.
2.1 Upload a File into Sub-folder of Document Library.
3 Update Meta Data of file programmatically
3.1 Check In a file if Library has Mandatory columns.
4 Full code
4.1 Share this:
4.2 Like this:
4.3 Related

Requirement:

Upload files into SharePoint Library Programmatically using C#

Assumptions:

Let us assume we already have a site and other variable properties as below.

  • SiteUrl: https://SharePointforfun.com
  • Library Name: Documents
  • File Name: TestDoc.doc
  • Country: India
  • Sub Folder Name: IT

That’s it for the Prerequisites, and now let us move ahead with the actual code.

C# Program to upload the file into SharePoint Document Library.

Step 1. Declare assemblies and Namespace: Declare assemblies from SharePoint as per below code snippet.

Using System;
Using System.SiteCollections.Generic;
Using System.Linq;
Using System.Text;
Using Microsoft.SharePoint; 
Using System.IO;
Using System.Collections;

Namespace UploadFiles
{
   Class Program
    {
      //your code goes here
    }
}

Step 2. Access your Site collection in code.

//Retrive sitecollection
using(SPSite site = new SPSite ("https://spforfun.com"))
{
  //Open Web
  using(SPWeb web=site.OpenWeb())
  {
    //Your remaining code goes here....
  }
}

Step 3. Read a file (which you want to upload) into bytes array using stream functions.

//Read the file using stream into a byte array
FileStream fs = File.OpenRead(@"c:\TestDoc.doc");
byte[] Content = new byte[fs.Length];
fs.Read(Content, 0, Convert.ToInt32(fs.Length));
fs.close();

Step 4. Get the document Library named “Documents”. At this location, your file will be uploaded.

//get library named "Documents"
SPList DocLib = web.Lists["Documents"];

Step 5. Add a file into Library called “Documents”

//Add a File
web.Files.Add(DocLinb.RootFolder + "/TestDoc.doc", Content, true);

In this way, you can upload a file into SharePoint document Library.

Now Lets go ahead and do some more stuff on this.

Upload a File into Sub-folder of Document Library.

Suppose we have a sub-folder named IT in our “Documents” Library. And we want to add our file into it, and below is the code used to add a file into sub-folder.

//Get Sub-folder of Library named "IT"
SPFolder subFolder = DocLib.RootFolder.SubFolders["IT"];
//Add a file into the sub-Folder.
SPFile file = subFolder.Files.Add(subFolder.URL, + "/TestFile.doc", Content, true);
subFolder.Update();

Update Meta Data of file programmatically

Let us update a metadata Property, Let’s say “Country” columns value we need to update.

//update metadata column Country
SPListItem item = DocLib.Items[file.UniqueId];
item["Country"] = "India";
item.Update();

//OR We can also Use method called Hash Table
var Metadata = new Hashtable{{"Country", "India"}};
//add a file now
web.Files.Add(DocLib.RootFolder + "/TestDoc2.doc", FileContent, Metadata, true);

Check In a file if Library has Mandatory columns.

if (file.CheckOutStatus != SPFile.SPCheckOutStatus.None)
{
   file.CheckIn("File uploaded Successfully!");
}

Publish a file : Please NOTE- only publish a file when minor versions are enabled.

//file.Publish("File published Successfully!");

Full code


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using System.IO;
using System.Collections;
 
namespace UploadFiles
{
 class Program
    {
      static void Main(string[] args)
        {
          //Get your Site collection
            using (SPSite site = new SPSite("http://spforfun.com"))
            {
                //Open Root web
                using(SPWeb web=site.OpenWeb())
               {
               
                // Read the file from the stream into the byte array
                FileStream fs= File.OpenRead(@"c:\TestDocDoc.doc");
                byte[] Content= new byte[fs.Length];
                fs.Read(Content, 0, Convert.ToInt32(fs.Length));
                fs.Close();
                //Get the documents Librarym named "Documents"
                SPList DocLib = web.Lists["Documents"];
                //Add the file
                web.Files.Add(DocLib.RootFolder + "/TestDoc.doc", Content, true);
 
                /*** If you want to add inside a folder: say "IT" *******/
                // Get the folder called "IT"
                SPFolder SubFolder = DocLib.RootFolder.SubFolders["IT"];
                //Add the file to the sub-folder
                SPFile file = SubFolder.Files.Add(SubFolder.Url + "/NewFile.doc", Content, true);
                SubFolder.Update();
 
                //IF you want to Update the Meta data column say "Country"
                SPListItem item = DocLib.Items[file.UniqueId];
                item["Country"] = "India";
                item.Update();
                // OR We can use the Hash Table
                var Metadata = new Hashtable { { "Country", "India" } };
                // Add the file
                web.Files.Add(DocLib.RootFolder + "/TestDoc2.doc", Content, Metadata, true);
 
                
                if (file.CheckOutStatus != SPFile.SPCheckOutStatus.None)
                {
                    file.CheckIn("File uploaded Successfully !");
                }
 
                
                //file.Publish("File published Successfully !");
 
              }
            }
        }
    }
}
  • If you are looking for a way to move files between two libraries in SharePoint using Powershell, you can find my another article: Move files in SharePoint using PowerShell. You can find detailed code here.

I hope you liked this (Programmatically Upload a File in SharePoint Document Library) article, and if you think this is useful to you then please hit a Like button or express your feelings with comment.

Share this:

  • Print
  • Twitter
  • Facebook
  • LinkedIn
  • WhatsApp
  • Telegram
  • Pinterest
  • Reddit

Like this:

Like Loading...

Related

6 thoughts on “Programmatically Upload a File in SharePoint Document Library.”

  1. mtv says:
    March 10, 2020 at 8:58 PM

    your post helps me a lot. thanks for sharing

    Loading...
    Reply
    1. SharePointGems says:
      May 20, 2020 at 8:11 PM

      Thank you very much!
      I am glaf to hear that.

      Loading...
      Reply
  2. Igwe Chisom Henry says:
    March 11, 2020 at 6:52 PM

    Nice bro keep it up

    Loading...
    Reply
  3. Pingback: Create Approval workflow in MS Flow Step-By-Step - SharePoint Gems
  4. Pingback: Retrieve SharePoint List Items using CSOM - SharePoint Gems
  5. Pingback: Retrieve all users from Site Collection using PowerShell - SharePoint Gems

Leave a ReplyCancel reply

  • Development
  • Migration
  • Poweer Apps
  • Power Automate
  • Power Platform
  • SharePoint 2013
  • SharePoint Administration
  • SharePoint Online
  • Tips
  • Uncategorized

Best of Computers

Blog Stats

  • 67,509 hits

Subscribe

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 1,433 other subscribers
Buy Me Coffee
©2025 SharePoint Gems | Powered by WordPress and Superb Themes!
%d