How to upload file programmatically to SharePoint Document Library using Server Object Model C#.Net


Posted on : Wed, 30th Sep 15 01:55 pm (Updated on : Wed, 30th Sep 15 01:55 pm) UTC
Author : Code2care
2314 votes

Upload or add file to SharePoint Document Library via Server Object Model

Below is a code snippet written in Visual Studio Console Application (C#.Net) which uses the SharePoint Server Object Model.
You can use the same code in a web part or extend it to add more functionality and validations. Make sure the SharePoint user has enough permissions (contribute ideally) to add documents, or use "RunWithElevatedPrivileges"

Name : Code to upload file to SharePoint Document library - using server Object Model
String site = "http://sharepointsiteurl";	//URL of SharePoint site
String library = "Shared Documents";            //Library Name
String filePath = @"C:\testfile.txt";           //Entire path of file to upload

try
{
	using (SPSite spSite = new SPSite(site))
        {
        	using (SPWeb spWeb = spSite.OpenWeb())
		{
			//Check if file exists in specified path
			if (!System.IO.File.Exists(filePath))
				Console.WriteLine("Error - Specified file not found.");

			//Get handle of library
	                SPFolder spLibrary = spWeb.Folders[library];

			//Extract file name (file will be uploaded with this name)
        	        String fileName = System.IO.Path.GetFileName(filePath);

                	//Read file for uploading
	                FileStream fileStream = File.OpenRead(filePath);

	                //Replace existing file
			Boolean replaceExistingFile = true;

			//Upload document to library
        	        SPFile spfile = spLibrary.Files.Add(fileName, fileStream, replaceExistingFile);
                	spfile.CheckIn("file uploaded via code");
                        spLibrary.Update();
		}
	}
        	Console.WriteLine("File uploaded successfully !!");
	        Console.ReadLine();
}
catch (Exception exp)
{
	Console.WriteLine("Error uploading file - " + exp.Message);
	Console.ReadLine();
}

Troubleshooting issues

  1. You should not run into any major issue if this is written in a web part code
  2. If using Console application, make sure Microsoft.SharePoint.dll reference is added
  3. Microsoft.SharePoint and System.IO is added in the using directive
  4. Console - If you get SharePoint System.IO.FileNotFoundException, make sure the build platform is changed to 64 bit (refer here for more details)
  5. Make sure RunWithElevatedPrivileges is used if you get access denied error

Code2care's mission is to share varied knowledge in technical and non-technical areas gathered during day-to-day learnings and development activities so that our visitors can leverage this portal to find solutions to their queries without re-inventing the wheel. Technical posts include Learnings, Tutorials, Video Tutorials, Code Snippets, Tips-n-tricks.

Follow us : Facebook - Twitter - Google +