How to upload file to SharePoint document library with Object Model


So far so good, it has been wonderful journey of learning SharePoint. With every end of day I learn something new and wants to share that with my readers. So here I am again showing you one more aspect of SharePoint programming. In my earlier post I had written about, Programming SharePoint Lists, in which I showed all the CRUD operations that can be done on SharePoint List. Here I shall be talking about the document libraries. Well they are also one type of the list , but the vast difference between them is that the Lists stored the structured data, well as Document Libraries are responsible for storing the unstructured data like documents or any other binary data. Their features and events are also different from the standard lists. In this short post , I will be teaching you the following:

  • how you can upload the files in the document library programmatically
  • how to create a new folder in the document library

So let us take one by one.

How to upload the files in the document library programmatically

With rich object model of SharePoint , this can be accomplished with few lines of code.So let us assume that you have FileUpload control of the, where the end user will be selecting the file. I have kept this control in the user control.This user controls also exposes other properties like SiteCollection,Web and DocumentLibraryPath. All these three properties are of String type. Let us see now what happens when user clicks on the Upload Button

Protected Sub BtnUpload_Click(ByVal sender As Object, ByVal e As EventArgs) Handles BtnUpload.Click

      If Not String.IsNullOrEmpty(_DocLibPath) Then
          If Not String.IsNullOrEmpty(Me.FileUpload1.FileName) Then

              Dim objSiteCollection As New SPSite(_SiteCollection)
              Dim objWeb As SPWeb
              objWeb = objSiteCollection.AllWebs(_Web) 

              If Not objWeb Is Nothing Then
                      objWeb.AllowUnsafeUpdates = True
                      objWeb.Files.Add(_DocLibPath & Me.FileUpload1.FileName, Me.FileUpload1.FileBytes) 
                       objWeb.AllowUnsafeUpdates = False
                  Catch ex As Exception
                  End Try
              End If
              Label1.Text = "Please provide the file name"
          End If

          Throw New Exception("Please define the property value of DocumentLibararyPath")
      End If

  End Sub

After initializing the SPSite and SPWeb objects, with the property values of the user control. We add new Item to FilesCollection property of SPWeb object. This method accepts the document name along with its full path and the second parameter is the array of bytes, which is the actual content of the document.Notice one thing here is that I am calling the Add method after I have set the AllowUnsafeUpdates property of the SPWeb object to True. This is very important because of Security issues,as your code is going to update the SharePoint objects without any pre authentication. SharePoint will throw the exception "The security validation for this page is invalid. Click Back in your Web browser, refresh the page, and try your operation again." Once the file is uploaded I am setting back the property to false. So with just few lines of code, we have uploaded a new document to the SharePoint document library. Now let us jump to the next section.

How to create new folder in SharePoint document library

If Not String.IsNullOrEmpty(TxtFolder.Text) Then
                        Dim objFolders As SPFolderCollection = objWeb.Folders
                        Dim CheckIfFolderExists = From folder As SPFolder In objFolders _
                                                Where folder.Name.Equals(Me.TxtFolder.Text)
                        If CheckIfFolderExists.Count > 0 Then
                            objWeb.AllowUnsafeUpdates = True
                            objFolders.Add(_DocLibPath & TxtFolder.Text)
                            objWeb.AllowUnsafeUpdates = False
                            Me.Label1.Text = "Folder Already Exists"
                        End If

End If

After checking whether folder with the same name already exists in the document library through Linq expression. I use SPFolderCollection object and initialize this object with the SPWeb.Folders property. Again using the Add method of the SPFolderCollection which accepts the full path of the document library along with the folder name. Again it is being done by setting the AllowUnsafeUpdates to true and false.


Document library has an important role in SharePoint. It is good to have the knowledge of it and how can you perform the tasks on these objects programmatically. Download the sample code from here. Please set all the user control properties in your aspx page before running the solution.



4 thoughts on “How to upload file to SharePoint document library with Object Model

  1. I have been looking for a solution like what you have created for a few days. It seems to be the closest to what i need to acomplish. Thank you for your hard work. However I’m new to SP and prog. I wanted to know if there would be a way to explain how this code is to be used and how i can use it to acomplish the goals that are needed. I need to upload in lack of a better phrase a ton of documents from a file system into a sharepoint doc lib and also be able to create the folder structure as well. Any help you can provide would be great.

    • Matthew,
      Thanks for your appreciation. Well it is pretty easy you just need to write one recursive function , which can accept the directory path and then using Linq to Objects you can query the file system. Once you get the all the files in the linq query object , loop through that object and add the code within the loop to upload the files present in the query object to the document library.

      Hope I have answered your question. Do let me know if you need any further assistance on this.

  2. How can i get in touch with outside of the comments of this site to give you more information about what I’m trying to complete? Would email be ok? Some of what you are talking about makes sense to me, however still being new at this now 100 percent sure what to do next.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s