How to upload documents to SharePoint document library programmatically with metadata

In this SharePoint tutorial, We will discuss how to upload a file to SharePoint 2016 document library programmatically using file upload control.

Here we will create a visual web part and we will use the SharePoint server object model code to upload a document and set up metadata programmatically in the SharePoint document library.

We will also discuss how to set up metadata while uploading the file to SharePoint 2016 document library programmatically. We will update document library metadata programmatically for choice column.

Here in my SharePoint 2016 site collection, I have a document library which has two metadata choice column: Language (English/Hindi/Kannad) & Department (IT/HR/Finance).

Here, User will upload file to the document library and at the same time, it will also set Language and Department column values.

For this first, we will create a visual web part using visual studio 2017 and design the input form for a user to upload a file to SharePoint 2016 document library.

Create Visual Web Part SharePoint 2016

First we will create the visual web part using Visual Studio 2017.

Open Visual Studio 2017 and go to File -> New -> Project…

In the New Project dialog box, expand Visual C# -> Office/SharePoint -> SharePoint Solutions. And then choose SharePoint 2016 – Empty Project like below:

upload file in sharepoint document library programmatically
upload file in sharepoint document library programmatically

Then in the Next screen, Provide a local SharePoint 2016 site URL and choose Farm Solution. And click on OK. Then the Empty project will get created.

Once the SharePoint 2016 empty project got created we can add Visual web part into the solution.

Now to add a Visual web part to the project, Go to the “Solution Explorer” -> Right click on your project name -> “Add” -> “New Item” as like below.

In the “Add New Item” dialog box, Select the “Visual Web Part (Farm Solution Only)“. Enter the “Name” of your visual web part and then click on “OK” as shown in below.

upload a file programmatically in sharepoint
SharePoint 2016 Create visual web part

Once you add the visual web part, there will be a user control where we can design our form and write code to upload the file to SharePoint 2016 document library.

Design Custom Form to Upload File

In the visual web part we can design the form in the .ascx file. Here we will add below controls.

  • fileUpload: This control is used for uploading a file.
  • Button: This control helps to create a button. So that when a user uploads a file and then after clicking on the button, the file will save in the particular document library.
  • Label: If some error will come after deploying the code, then this control helps to show the error message.
<table>
    <tr>
        <td>Select File:</td>
        <td><asp:FileUpload ID="fuUploadFile" runat="server" </td>
    </tr>
    <tr>
        <td></td>
        <td><asp:Button ID="btnSave" runat="server" Text="Save" Width="105px" OnClick="BtnSave_Click1" /></td>
    </tr>
    <tr>
        <td><asp:Label ID="lblMessage" runat="server" Text=""></asp:Label></td>
    </tr>
    <tr>
        <td><asp:Label ID="lblCheckMesaage" runat="server" Text=""></asp:Label></td>
    </tr>
</table>

Code to upload file in SharePoint document library programmatically

Below SharePoint 2016 server object model code to upload a file to SharePoint 2016 Document Library programmatically.

using Microsoft.SharePoint;
using System;
using System.IO;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

namespace TSInfo_Intranet.File_Upload
{
    public partial class File_UploadUserControl : UserControl
    {
        string siteURL = "";
        string listTitle = "Company Document";

        protected void Page_Load(object sender, EventArgs e)
        {

if (!IsPostBack)
            {
}
        }

        protected void BtnSave_Click1(object sender, EventArgs e)
        {
            uploadDocument();

        }

        public void uploadDocument()
        {
            if (fuUploadFile.PostedFile != null && 

fuUploadFile.HasFile)
            {
                try
                {
                    SPSite siteCollection = SPContext.Current.Site;
                    SPWeb web = SPContext.Current.Web;
                    SPList spList = web.Lists.TryGetList(listTitle);
                    {
                        {
                            byte[] contents;
                            using (Stream filestream = 

fuUploadFile.PostedFile.InputStream)
                            {
                                contents = new byte[filestream.Length];
                                filestream.Read(contents, 0, 

(int)filestream.Length);
                                filestream.Close();

                                string fileName = Path.GetFileName

(fuUploadFile.PostedFile.FileName);
                                string fileNameWithoutExtension = 

Path.GetFileNameWithoutExtension

(fuUploadFile.PostedFile.FileName);
                                spList.RootFolder.Files.Add

(spList.RootFolder.Url + "/" + fileName, contents, true);
                                spList.Update();
                            }
                        }
                    }
                }

                catch (Exception ex)
                {

                    lblMessage.Text = ex.StackTrace;
                    lblCheckMesaage.Text = ex.Message;
                }
            }
            else
            {
                lblMessage.Text = "Select a File";
            }
        }
    }
}

Set metadata column programmatically in SharePoint 2016 document library (Choice Column)

Here we have added two dropdown list to the visual web part for setting up metadata programmatically.

<table>
<tr>
    <td>Language:</td>
    <td><asp:DropDownList ID="ddllang" runat="server">
        <asp:ListItem>Select Language</asp:ListItem>
        <asp:ListItem>English</asp:ListItem>
        <asp:ListItem>Hindi</asp:ListItem>
        <asp:ListItem>Kannad</asp:ListItem>
        </asp:DropDownList></td>
</tr>
    <tr>
        <td>Document Type:</td>
        <td><asp:DropDownList ID="ddldoctype" runat="server">
            <asp:ListItem>Select Document Type</asp:ListItem>
            <asp:ListItem>IT</asp:ListItem>
            <asp:ListItem>HR</asp:ListItem>
            <asp:ListItem>FINANCE</asp:ListItem>
            </asp:DropDownList></td>
    </tr>
</table>

Set Metadata of Choice field using SharePoint 2016 server object model code

Below SharePoint 2016 server object model Code, you can use for set the metadata to choice field programmatically.

public void SetupMetadata(SPWeb spWeb, SPList spList, string title, string fileNameWithoutExtension)
        {
            try
            {
                string fullFilePath = siteURL + spList.RootFolder.Url + "/" + title;
                SPFile newFile = spWeb.GetFile(fullFilePath);
                SPListItem item = spList.Items[newFile.UniqueId];
                item["Title"] = fileNameWithoutExtension;
                item["Language"] = spList.Fields
["Language"].GetFieldValue(ddlLanguage.SelectedValue);
                item["Department"] = spList.Fields
["Department"].GetFieldValue(ddlDepartment.SelectedValue);
                item.Update();
                spWeb.Update();
              }
            catch (Exception )
            {
                lblMessage.Text = "Error ocuured";             
            }  
        }

Deploy Visual web part to SharePoint 2016 using Visual Studio 2017

To deploy the solution of File Upload and set metadata, Go to the “Solution Explorer“-> “Right Click on your Solution name“-> “Deploy” as shown below.

Note: It Should be better if you will “Build” or “Rebuild” your solution before deploying. To build the solution, also you can follow the same process of deploy. But instead of deploy, you have to select the “Build” or “Rebuild” option.

How to deploy the solution in visual studio 2017
How to deploy the solution in visual studio 2017

In this approach you can deploy visual web part to SharePoint 2016 development server. If you want to deploy visual web part to any other server like production server, then follow, PowerShell Script to deploy WSP Solution in SharePoint 2013.

Once the deploy will over, create a new “Web Part Page” in your SharePoint Site and then click on “Add a Web Part” in that web part page.

Working with web part page and wiki page in SharePoint 2016

Add Visual Web Part to SharePoint 2016 web part page

Go to the “Custom” web part from “Categories” template. Then it will show your project name. Click your project name and add it by using “Add” button as like below screenshot.

Deploy the solution in visual studio 2017
Deploy the solution in visual studio 2017

Once you add the visual web part, you can see the form like below screenshot. Once you will fill all the field value and then save, the file will upload in your SharePoint 2016 Document Library with metadata.

SharePoint 2013 Get choice column programmatically
Get choice column programmatically sharepoint

Open the particular SharePoint 2016 document library, you can see the file like below:

Get choice column programmatically using C#
Get choice column programmatically using C#

You can also see in the below screen shot, the edit document properties page looks like below:

upload file in sharepoint document library programmatically c#
upload file in sharepoint document library programmatically c#

You may like following SharePoint server object model tutorials:

Conclusion

This SharePoint 2016 tutorial, we discussed how to upload file in SharePoint 2016 document library programmatically c#.net using SharePoint 2016/2013 server object model code.

We saw, how to create and deploy visual web part to SharePoint 2016. How to set value for metadata column programmatically using SharePoint 2016 server object model.

>