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
- You should not run into any major issue if this is written in a web part code
- If using a Console application, make sure Microsoft.SharePoint.dll reference is added
- Microsoft.SharePoint and System.IO is added in the using directive
- Console - If you get SharePoint System.IO.FileNotFoundException, make sure the build platform is changed to 64 bit (refer here for more details)
- Make sure RunWithElevatedPrivileges is used if you get access denied error
This is not an AI-generated article but is demonstrated by a human.
Please support independent contributors like Code2care by donating a coffee.
Buy me a coffee!

Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!