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;
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: batchNode.InnerXml = xmlCommand;
XmlNode resultNode = listService.UpdateListItems(listName, batchNode);
if ((resultNode != null) && (resultNode.FirstChild.FirstChild.InnerText == "0x8107090d") || (resultNode.FirstChild.FirstChild.InnerText == "0x00000000"))
{
}
else
{
}
}
catch (Exception)
{throw; } }
Method Calling: Call method like
CreateFolderOnSharepoint("Shared Documents","MyTestFolder");
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 = “https: 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(”C\\MyTestDocument.doc”,"Shared Documents");
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(“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:
- Right click on your project solution name.
- Go to ADD > Service Reference.
- Now click on Advance button on left bottom.
- Again click on Add Web Reference button on left bottom.
- 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.
- 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.