Click here to Skip to main content
15,116,654 members
Articles / Productivity Apps and Services / Sharepoint
Article
Posted 18 Mar 2016

Tagged as

Stats

17.4K views
2 bookmarked

SharePoint .NET Integration

Rate me:
Please Sign up or sign in to vote.
4.50/5 (2 votes)
18 Mar 2016CPOL3 min read
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.

Image 1

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);

C++
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

C++
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:

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

or

C++
string destinationFolderPath = "https://yoursharepointdomain/<ParentName>/<ChildFolder>;
C++
public void UploadFileOnSharePoint(string sourceFilePath, string FolderName)
        {
            string destinationFolderPath = "https://yoursharepointdomain/"+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

C++
UploadFileOnSharePoint("C\\MyTestDocument.doc","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.

C++
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

C++
GetFilesFromSharePoint("Shared Documents");

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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Manu Abhishek Dwivedi
Software Developer (Senior) Infosys
India India
I am a coding maniac. Always love to learn new technologies .

Comments and Discussions

 
QuestionGetting Error in List Pin
Member 1402356328-Oct-18 9:03
MemberMember 1402356328-Oct-18 9:03 
GeneralFor Getting File As Array Pin
Manu Abhishek Dwivedi22-Mar-16 20:39
professionalManu Abhishek Dwivedi22-Mar-16 20:39 
QuestionUploading files - checked out? Pin
JJJX21-Mar-16 7:29
MemberJJJX21-Mar-16 7:29 
AnswerRe: Uploading files - checked out? Pin
Manu Abhishek Dwivedi21-Mar-16 20:32
professionalManu Abhishek Dwivedi21-Mar-16 20:32 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.