Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

SharePoint .NET Integration

0.00/5 (No votes)
18 Mar 2016 1  
Integrating SharePoint web service with .NET Project to perform list creation, document get and upload tasks programmatically .

Introduction

I am providing sample code to integrate SharePoint into your project for providing Document upload, document listing and creating folder on SharePoint programmatically using C# .

Background

SharePoint server provide us facility to store our documents securely and safely.Sometimes we have to integrate SharePoint services inside our project so that user can access document without moving throw SharePoint server.

Requirement

You should have a user account on given SharePoint server and you have to have sufficient permission to create, upload and edit document or folder in order to run that code.

Create Folder on SharePoint

Purpose

Creating a folder in SharePoint under a folder or list.

Service Reference

Add a lists.asmx web service reference in your project solution with the given URL and named it to ListServiceReference.

https://yoursharepointdomain/_vti_bin/lists.asmx

C# Code

Copy below code and paste in your solution. Resolve some XML related references already present in .Net framework. In below code I am creating a child folder under a parent folder or List =“Shared Documents”, you can use any one of your folder or list in place of that but this should be in from of URL format like:

batchNode.SetAttribute("RootFolder", "https://yoursharepointdomain/<FolderName>");

or

batchNode.SetAttribute("RootFolder", "https://yoursharepointdomain/<ParentFolder>/<ChildFolder>");

Example

batchNode.SetAttribute("RootFolder", https://yoursharepointdomain/Shared Documents);

public void CreateFolderOnSharepoint(string listName, string newFolderName)
        {
            try
            {
                ListServiceReference.Lists listService = new ListServiceReference.Lists();
                listService.Url = "https://yoursharepointdomain/_vti_bin/lists.asmx";
                listService.Credentials = System.Net.CredentialCache.DefaultCredentials;
                //Correct invalid characters
                newFolderName = newFolderName.Replace(":", "_");
                string xmlCommand = string.Format("<Method ID='1' Cmd='New'><Field Name='ID'>New</Field><Field Name='FSObjType'>1</Field><Field Name='BaseName'>{1}</Field></Method>", newFolderName);
                XmlDocument doc = new XmlDocument();
                System.Xml.XmlElement batchNode = doc.CreateElement("Batch");
                batchNode.SetAttribute("OnError", "Continue");
                batchNode.SetAttribute("RootFolder", https://yoursharepointdomain/ + listName);
                batchNode.InnerXml = xmlCommand;
                XmlNode resultNode = listService.UpdateListItems(listName, batchNode);
                if ((resultNode != null) && (resultNode.FirstChild.FirstChild.InnerText == "0x8107090d") || (resultNode.FirstChild.FirstChild.InnerText == "0x00000000"))
                {
                    // Folder successfully created
                }
                else
                {
                    //error
                    //resultNode.OuterXml
                }
            }
            catch (Exception)
            {throw; } }

Method Calling: Call method like

CreateFolderOnSharepoint("Shared Documents","MyTestFolder");

Create Folder On SharePoint

Refresh the page after successfully running the code you will be now able to see the new folder.

Upload File on SharePoint

Purpose

Uploading file on SharePoint under a folder or list.

 

Service Reference

Add a copy.asmx web service reference in your project solution with the given URL and named it to CopyServiceReference.

https://yoursharepointdomain/_vti_bin/copy.asmx

C# Code

Copy below code and paste in your solution. Resolve some XML related references already present in .Net framework. You can use any one of your destination folder or list but this should be in from of URL format like:

string destinationFolderPath = "https://yoursharepointdomain/<FolderName>;

or

string destinationFolderPath = "https://yoursharepointdomain/<ParentName>/<ChildFolder>;
public void UploadFileOnSharePoint(string sourceFilePath, string FolderName)
        {
            string destinationFolderPath = &ldquo;https://yoursharepointdomain/&rdquo;+FolderName;
            string[] strSplit = sourceFilePath.Split('\\');
            string destinationPath = destinationFolderPath + "/" + strSplit[strSplit.Length - 1];
            CopyServiceReference.Copy copyReference = new CopyServiceReference.Copy();
            try
            {
                string destination = destinationPath;
                string[] destinationUrl = { destination };
                byte[] fileBytes = GetFileFromFileSystem(sourceFilePath);
                copyReference.Url = "https://yoursharepointdomain/_vti_bin/copy.asmx";
                copyReference.Credentials = System.Net.CredentialCache.DefaultCredentials;
                CopyResult[] cResultArray = null;
                FieldInformation documentTypeField = new FieldInformation();
                documentTypeField.DisplayName = "DocumentType";
                documentTypeField.Type = FieldType.Text;
                documentTypeField.Value = " ";
                FieldInformation titleField = new FieldInformation();
                titleField.DisplayName = "Title";
                titleField.Type = FieldType.Text;
                titleField.Value = strSplit[strSplit.Length - 1];
                //Linked Metadata For that file
                FieldInformation[] filedInfo = { documentTypeField, titleField };
                //Copy or upload file from your system to SharePoint server folder
                copyReference.CopyIntoItems(destination, destinationUrl, filedInfo, fileBytes, out cResultArray);
            }
            catch (Exception ex)
            {
                //error
            }
            finally
            {
                if (copyReference != null)
                    copyReference.Dispose();
            }         
        }

Method Calling: Call method like

UploadFileOnSharePoint(&rdquo;C\\MyTestDocument.doc&rdquo;,"Shared Documents");

Upload Document On SharePoint

Refresh the page after successfully running the code you will be now able to see the new file.

Get Files from SharePoint

Purpose

Get list of all items under a SharePoint folder or list. (e.g.: ‘Shared Documents’)

Service Reference

Add a lists.asmx web service reference in your project solution with the given URL and named it to ListServiceReference.

https://yoursharepointdomain/_vti_bin/lists.asmx

C# Code

Copy below code and paste in your solution. Resolve some XML related references already present in .Net framework. Also add a Label in your ASPX page with ID=lblFiles. In below code I am created a table using string to list all items as in tabular format.

public void GetFilesFromSharePoint(string DirectoryName)
        {
            try
            {             
                using (var client = new ListServiceReference.Lists())
                {
                    client.Credentials = System.Net.CredentialCache.DefaultCredentials;
                    client.Url = "https://yoursharepointdomain/_vti_bin/lists.asmx";
                    XmlNode ndListItems = null;
                    XmlDocument xdoc = new XmlDocument();
                    XmlNode ndQuery = xdoc.CreateNode(XmlNodeType.Element, "Query", "");
                    XmlNode ndViewFields = xdoc.CreateNode(XmlNodeType.Element, "ViewFields", "");
                    XmlNode ndQueryOptions = xdoc.CreateNode(XmlNodeType.Element, "QueryOptions", "");
                    ndQuery.InnerXml = "";
                    ndViewFields.InnerXml = "";
                    ndQueryOptions.InnerXml = "<IncludeAttachmentUrls>TRUE</IncludeAttachmentUrls>";
                    ndListItems = client.GetListItems(DirectoryName, "", ndQuery, ndViewFields, "1000", ndQueryOptions, null);
                    if (ndListItems != null)
                    {
                        string strMain = "<table><tr><th>Title</th></tr>";
                        foreach (XmlNode node in ndListItems.ChildNodes)
                        {
                            XmlNodeReader objReader = new XmlNodeReader(node);
                            while (objReader.Read())
                            {
                                if (objReader["ows_EncodedAbsUrl"] != null && objReader["ows_LinkFilename"] != null)
                                {
                                    string strURL = objReader["ows_EncodedAbsUrl"].ToString();
                                    string strFileName = objReader["ows_LinkFilename"].ToString();
                                    strMain = strMain + "<tr><td><a href=\"" + strURL + "\">" + strFileName + "</a></td></tr>";
                                }
                            }
                        }
                        lblFiles.Text = strMain + "</table>";
                    }
                }
            }
            catch (Exception)
            { throw; }  }

Method Calling: Call method with folder name like

GetFilesFromSharePoint(&ldquo;Shared Documents&rdquo;);

Above code will append a table on web page and list those files which is inside that folder as a link to SharePoint site for that document.

How to add web reference?

If you do not have any idea about how to add web service web reference then you can check on MSDN or follow these steps:

  1. Right click on your project solution name.
  2. Go to ADD > Service Reference.
  3. Now click on Advance button on left bottom.
  4. Again click on Add Web Reference button on left bottom.
  5. Under Web Reference window put service URL in URL textbox and hit enter, now you will be able to view all methods related to that service just below that URL textbox now see the textbox in right hand side just above on Add Reference button. Now enter a name for that service or use above mention names which I mention in code as service name then click on Add Reference button.
  6. Now you will be able to check service in your project

Points of Interest

I have created a very short code so that you can easily use this in your project just by changing some values. Its like plug and play.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here