Programatically upload file to SharePoint Document library

By Jatin Prajapati

Shows how to upload a file to SharePoint Document Library programmatically.

While developing custom web parts, some time we want to upload a file like pdf, image or word document to SharePoint Document Library. Here in the below code using C# I'll show you how to achieve this.

string filePath = @"C:\pdf files\myFile.pdf";
string fileName = "myFile.pdf";
string documentLibraryName = "Shared Documents";
SPWeb web = SPContext.Current.Web;
FileStream fs = File.Open(filePath, FileMode.Open, FileAccess.Read);
byte[] fileContent = new byte[fs.Length];
fs.Read(fileContent, 0, fileContent.Length);
web.Files.Add(string.Format("{0}/{1}/{2}",web.Url, documentLibraryName, fileName),fileContent, false);


In the above code, the Files.Add method has three parameters.
1. File Url - the file's url where to create
2. File content - a byte arrary containing file contents
3. Boolean value true or false - which indicate, if true then, it will overwrite any existing file with the same name of your file and if false, the throws an exception.

Programatically upload file to SharePoint Document library  (3109 Views)