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
More Posts related to SharePoint,
- error CAML Query containing special characters
- [Solved] SharePoint Illegal operation attempted on a registry key that has been marked for deletion
- Trigger Flow on selected Listitem from SharePoint view - create button with JSON column formatting
- SharePoint Excel error - The workbook cannot be opened because it contains the following features that are not supported by Excel in the browser
- Send Email with attachment using SharePoint PowerShell, SMTP server
- How to show or hide columns in SharePoint Online List Library from
- SharePoint excel error - A problem occurred while connecting to the server. If the problem continues, contact your administrator.
- How to get SharePoint Online user details from person or group column using REST API
- How to get SharePoint List Item URL using PowerShell
- How to get the SharePoint Tenant Login URL
- Special character & not working with SharePoint REST API
- How to disable SharePoint subsite creation option for owners
- Managed Metadata error - The data returned from the tagging UI was not formatted correctly
- Deploy SharePoint wsp solution package using PowerShell
- How to create classic site in SharePoint Online
- See actual SharePoint error exception modify web.config
- 'Edit Document' Requires a Windows Sharepoint Services-compatible application and Microsoft Internet Explorer 6.0 or higher
- How to enable anonymous public access for SharePoint Online site collection, file, folder without login ?
- SharePoint installation error - Setup is unable to proceed due to the following error This product requires Microsoft .Net Framework 4.5
- How to add animated Gif to SharePoint Online Page
- [Solved] SharePoint Search Internal server error exception
- How to create SharePoint Document Library
- SharePoint - Use Today's Date Time in list view filter and calculated column
- How to redirect SharePoint Site Collection to different URL
- SharePoint error cannot connect to the configuration database
More Posts:
- How to Right Click on Mac Desktop? - MacOS
- PHP drag and drop file upload tutorial using dropzone.js - PHP
- How to uninstall/remove or disable Microsoft Teams - Teams
- Setup synonyms or alias or thesaurus in SharePoint - SharePoint
- How to add Back Button on Toolbar in Android [Tutorial] - Android
- [Solved] Mic not working on iPhone 7 after iOS 14 upgrade - Apple
- 12 August - International Youth Day celebrated worldwide - News
- How to make jsfiddle bootstrap ready - CSS