How to upload file to SharePoint document library with Object Model

Goldytech
Posted by in SharePoint category on for Beginner level | Views : 17844 red flag

In this article , I show you how you can upload a file to SharePoint document library and also how you can create the new folder in the document library
Introduction
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 asp.net, 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
                  Try 
                      objWeb.AllowUnsafeUpdates = True
                      objWeb.Files.Add(_DocLibPath & Me.FileUpload1.FileName, Me.FileUpload1.FileBytes) 
                       objWeb.AllowUnsafeUpdates = False
                  Catch ex As Exception
                  Finally
                      objSiteCollection.Dispose()
                      objWeb.Dispose()
                  End Try
              End If
          Else
              Label1.Text = "Please provide the file name"
          End If

      Else
          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
                        Else
                            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.
Closure
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.

Cheers!

Page copy protected against web site content infringement by Copyscape

About the Author

Goldytech
Full Name: Muhammad Afzal Qureshi
Member Level: Bronze
Member Status: Member
Member Since: 8/4/2009 10:58:17 PM
Country: India

http://goldytech.wordpress.com
Hello Everyone Myself Muhammad Afzal , aka GoldyTech. Thats my pen name. I reside in India and work as a solution Architect on .NET platform. I hope you must have enjoyed reading my blog. Please leave your comments or suggestions good or bad and help me to improve

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)