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


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

Below is a code snippet is 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 a 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
Advertisements
Try Out Code2care Dev Tools:

Advertisements



Android Java Linux Microsoft Google Python macOS Notepad++ Microsoft Teams CSS PHP SharePoint Html Linux C Programs Bootstrap jQuery Sublime Android Studio Facebook Eclipse WhatsApp News MySQL Json HowTos JavaScript FTP S3


Advertisements


Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and Software Developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include Learnings, Tutorials, Trouble-Shooting steps, Video Tutorials, Code Snippets, How Tos, Blogs, Articles, etc.
🎉 We are celebrating the 10th years of Code2care! Thank you for all your support! We hope we made a difference.
We strong support Gender Equality & Diversity.

We stand in solidarity with Ukraine - Make a donation to UNHCR - https://donate.unhcr.org/in/en-in/ukraine-emergency