Upload a Document to the SharePoint Document Library using a Webservice

Posted by: Harsh Bardhan , on 4/5/2009, in Category SharePoint
Views: 86084
Abstract: Many a times, we may want to upload documents in a SharePoint server and place these documents in a document library. Document Libraries can consist of different files. The best part about this is that we can share these different files from the document library with other team members . In this article, we will discuss how to add a document to a SharePoint document library through a WebService.
Upload a Document to the SharePoint Document Library using a Webservice
 
                      
Many a times, we may want to upload documents in a SharePoint server and place these documents in a document library. Document Libraries can consist of different files. The best part about this is that we can share these different files from the document library with other team members . In this article, we will discuss how to add a document to a SharePoint document library through a WebService.
Update: This article does not use a Webservice, but instead uses the SharePoint API. Apologies for the incorrect title.
This article will discuss only  about adding documents using WebServices, however we can similarly upload documents using WCF services or through Web pages. We can also upload documents directly using the Upload menu from the SharePoint Interface. You can see interface for adding documents directly using the SharePoint interface below.
SharePoint Interface   
Let us see how to add documents to the Document Library using a WebService
Step 1: At first we will Create a New ASP.Net WebService Application. Open Visual Studio. File > NewProject> Select the language (C# or VB.NET) > Select Web Template >Select ASP.Net WebService Application.
Add WS
Step 2: Name it as UploadFileService and specify the location where you want to save that project. This step will create a Service1.asmx file.
Step 3: The Service1.asmx file by default will contain a HelloWorld method as shown below:
C#
[WebMethod]
public string HelloWorld()
{
    return "Hello World";
}       
 
VB.NET
<WebMethod> _
Public Function HelloWorld() As String
      Return "Hello World"
End Function
 
Step 4: We will change the method name to “UploadFileToDocmentLibrary” and the return type to void. So now our method will look like this.
 
C#
[WebMethod]
public void UploadFileToDocmentLibrary()
{
 
}
VB.NET
<WebMethod> _
Public Sub UploadFileToDocmentLibrary()
 
End Sub
 
Step 5: Add a reference to the Microsoft. SharePoint dll as shown in screenshot below and add the Namespace to your .cs or .vb file. This namespace is required to be used in the SharePoint Site
 
C#
using Microsoft.SharePoint;
 
VB.NET
Imports Microsoft.SharePoint
 
 
Add Reference
 
Step 6: Now add code in “UploadFileToDocmentLibrary“ method for connecting to your SharePoint site and adding a document. We can upload the document from the Fileupload control also, but here we will take the data from a bytearray directly.
 
Our Complete web method will look like this.
 
C#
 
[WebMethod]
public void UploadFileToDocmentLibrary()
{
    //Referring Top level sharepoint site
    //Change URI according to your sharepoint site
 
    using (SPSite sharePointtopLevelSite = new SPSite("http://localhost"))
    {
        //Will get Website collection inside top level site
        //Here my Toplevel site contains a website named test .
        //Change name according to your site settings
        SPWeb websiteCollection = sharePointtopLevelSite.AllWebs["test"];
        websiteCollection.AllowUnsafeUpdates = true;
        websiteCollection.Lists.IncludeRootFolder = true;
 
        //Will get List collection inside a website
        //Here my Toplevel site contains a List named tree .
        //Change name according to your site settings
        SPList docLibrary = websiteCollection.Lists["Tree"];
 
 
        //Here we are converting a Text to Byte Array
        //We can get byte array from Fileupload control of asp.net also
        //Add Reference to System.Text Namespace
        Byte[] contentArray = Encoding.ASCII.GetBytes("Hello Sharepoint.");
 
        // Uploading the file to SharePoint doclib
        SPFile file = websiteCollection.Files.Add(websiteCollection.Url.ToString() + "/" + docLibrary.Title.ToString() + "/" + "SharePointTest.txt", contentArray);
        file.Update();
 
    }
}
 
VB.NET
 
<WebMethod> _
Public Sub UploadFileToDocmentLibrary()
      'Referring Top level sharepoint site
      'Change URI according to your sharepoint site
 
      Using sharePointtopLevelSite As New SPSite("http://localhost")
            'Will get Website collection inside top level site
            'Here my Toplevel site contains a website named test .
            'Change name according to your site settings
            Dim websiteCollection As SPWeb = sharePointtopLevelSite.AllWebs("test")
            websiteCollection.AllowUnsafeUpdates = True
            websiteCollection.Lists.IncludeRootFolder = True
 
            'Will get List collection inside a website
            'Here my Toplevel site contains a List named tree .
            'Change name according to your site settings
            Dim docLibrary As SPList = websiteCollection.Lists("Tree")
 
 
            'Here we are converting a Text to Byte Array
            'We can get byte array from Fileupload control of asp.net also
            'Add Reference to System.Text Namespace
            Dim contentArray() As Byte = Encoding.ASCII.GetBytes("Hello Sharepoint.")
 
            ' Uploading the file to SharePoint doclib
            Dim file As SPFile = websiteCollection.Files.Add(websiteCollection.Url.ToString() & "/" & docLibrary.Title.ToString() & "/" & "SharePointTest.txt", contentArray)
            file.Update()
 
      End Using
End Sub
 
 
Step 7: Run this application and Refresh your web page and you will get the file name ‘SharepointTest’ in your document library
 
Explorer
That's it!
If you liked the article,  Subscribe to the RSS Feed or Subscribe Via Email  
Harsh Bardhan (MCTS) has developed IT solutions with a diverse background in server side and client side development. He is currently working with SymphonyServices as a Software developer. Harsh continues to be an integral part of open forums on cutting-edge technology like Silverlight, including the .NET Framework and Web Services. Harsh has expertise with many Microsoft technologies, including .NET, LINQ, WCF Service, Silverlight and a strong background in SQLServer. 
Give a +1 to this article if you think it was well written. Thanks!
Recommended Articles


Page copy protected against web site content infringement by Copyscape


User Feedback
Comment posted by Steve on Sunday, April 26, 2009 12:58 AM
Create article.

Can you describe how you would set the "Title" field in the document library?
Comment posted by Bill on Tuesday, July 14, 2009 1:25 PM
Your example does not use a Webservice, it uses the SharePoint API. The difference is that your client must be on a SharePoint server.

To use a Webservice begin by right clicking on your project in VS and selecting "Add Web Reference". When prompted for a URL enter http://<your SharePoint server>/_vti_bin/Lists.asmx this will add a class to your project. There are many sources on the web that can finish telling you how to use a Webservice. This isn't one of them.
Comment posted by Sujan on Wednesday, July 22, 2009 1:14 AM
When I upload a xml document to library, Title field to set to filename (i.e, MyFile.xml) irrespective of the value set for the Title field.
Is this the limitation of MOSS? How can I set the Title field to user entered value other than filename. The behavious is same from Sharepoint UI as well.
Comment posted by David on Wednesday, August 26, 2009 7:43 AM
A little miss leading, you use the Sharepoint API, as mentioned by a previous comment. Could you change your article to reflect this fact?
Comment posted by dalvin on Thursday, December 3, 2009 5:50 AM
HI sir, can I ask If how will I download the file from sharepoint? thank you
Comment posted by chaitra on Friday, March 5, 2010 6:20 AM
Hi,When i invoke the UploadFileToDocmentLibrary() method i get a file not found exception.I checked the url and it is opening in the browser.I'm getting the same error when I try to implement this functionality in a website also.

I'm working on windows server 2008,IE8,IIS7

Kindly let me know how i can resolve this issue.
Comment posted by krisrajz on Tuesday, April 5, 2011 6:37 AM
I have got sharepoint service got installed in my server
What is required to try the above code in my computer?
Thank you
Regards
Raj
Comment posted by Ron on Friday, July 22, 2011 2:51 PM
This is not a WebService app. You are using SharePoint API and hence your app has to be deployed on the same server as the SharePoin Server. This fact has been mentioned by two other readers (David and Bill). Could you change your article to reflect this fact?
Comment posted by Carol Nadarwalla on Monday, July 25, 2011 8:07 AM
Thanks David, Bill and Ron. Since this is an old article and the author could not be contacted, we have added an update based om the feedback. Thanks again!
Comment posted by Bruno K. on Thursday, February 23, 2012 9:28 AM
Hello,

I would like to know if you hane any idea on how to upload documents to SharePoint using a Windows Phone 7 mobile.

Do I need a WebService or just the SharePoint site API?

Thanks in advance!

Best Regards,
Comment posted by Shanmugavel.C on Tuesday, January 28, 2014 5:32 AM
Pls suggest some ideas to upload the local file system doc to share point list using VBA Macro.

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel