Programmatically upload a file to Document Library

By Namwar Rizvi - Last updated: Saturday, January 10, 2009 - Save & Share - 19 Comments

Following is a utility function which you can use to upload a file programmatically in SharePoint document library. It has two parameters. First is the source file path and second is the target document library path. 

Following is an example call to this function:

UploadFileToDocumentLibrary(@”C:\test.txt”, @”http://home-vs/Shared Documents/textfile.txt”);

and here is the function

    public static bool UploadFileToDocumentLibrary(string sourceFilePath, string targetDocumentLibraryPath)

    {

        //Flag to indicate whether file was uploaded successfuly or not

        bool isUploaded = true;

        try

        {

            // Create a PUT Web request to upload the file.

            WebRequest request = WebRequest.Create(targetDocumentLibraryPath);

 

            //Set credentials of the current security context

            request.Credentials = CredentialCache.DefaultCredentials;

            request.Method = “PUT”;

 

            // Create buffer to transfer file

            byte[] fileBuffer = new byte[1024];

 

            // Write the contents of the local file to the request stream.

            using (Stream stream = request.GetRequestStream())

            {

                //Load the content from local file to stream

                using (FileStream fsWorkbook = File.Open(sourceFilePath, FileMode.Open, FileAccess.Read))

                {

                    //Get the start point

                    int startBuffer = fsWorkbook.Read(fileBuffer, 0, fileBuffer.Length);

                    for (int i = startBuffer; i > 0; i = fsWorkbook.Read(fileBuffer, 0, fileBuffer.Length))

                    {

                        stream.Write(fileBuffer, 0, i);

                    }

 

                }

            }

 

            // Perform the PUT request

            WebResponse response = request.GetResponse();

 

            //Close response

            response.Close();

        }

        catch (Exception ex)

        {

            //Set the flag to indiacte failure in uploading

            isUploaded = false;

        }

 

        //Return the final upload status

        return isUploaded;

    }

Share
Posted in C# • Tags: , Top Of Page

19 Responses to “Programmatically upload a file to Document Library”

Comment from DuFFeR
Time January 12, 2009 at 7:14 am

can you please guide how can we update the other fields of the library as well
that document library where file is uploaded also has some custom columns, e-g file name, author, document version, product details, document description
when i upload a file it uploads the file and i need to insert those fields as well programatically
can you please guide towards this solution?

Comment from SG
Time January 12, 2009 at 3:29 pm

Can you guide on how can I get the item ID of this newly added file? I would need the ID so that locate the item in the document library and set some of the custom column values for this file.

Comment from ab
Time February 10, 2009 at 4:02 pm

Thanks for the nice post. My document library has other Fields(FirstName, LastName, DOB). How can i also upload these fields value at the same time when upload the file. Please help me.

Comment from Sandeep
Time March 12, 2009 at 5:45 am

I am getting below error while using the code…
The remote server returned an error: (400) Bad
Request

Comment from sona1
Time April 15, 2009 at 1:02 pm

Hi..I tried to upload file to document library programmatically as described above…the code works without errors, but the file is actually not added to the doc library…
Please help

Comment from joeygUrL
Time July 5, 2009 at 10:12 pm

Hi! I also had the same problem like Sona1. I added the “stream.Close();” within the “using” block and it worked afterwards. It basically flushed the changes into the stream before it closed it. See code below:

using (Stream stream = request.GetRequestStream())

{

//Load the content from local file to stream

using (FileStream fsWorkbook = File.Open(sourceFilePath, FileMode.Open, FileAccess.Read))

{

//Get the start point

int startBuffer = fsWorkbook.Read(fileBuffer, 0, fileBuffer.Length);

for (int i = startBuffer; i > 0; i = fsWorkbook.Read(fileBuffer, 0, fileBuffer.Length))

{

stream.Write(fileBuffer, 0, i);

}
}
stream.Close(); //Added this line – joeygUrL
}

Comment from bhuvan
Time September 1, 2009 at 2:45 pm

Thanks for the post! Helped me a lot.

Comment from dishashah08
Time September 30, 2009 at 6:33 pm

Hey

I have one Question .Can we upload remote or network drive files to Sharepoint Library?

Comment from Anu
Time October 12, 2009 at 10:29 am

I m geeting error unable to connect to remote server.

Comment from Elona
Time November 4, 2009 at 10:00 am

Hi, I am getting an error “Unauthorized (401)) while I can upload files from the Sharepoint Interface that is not programatically.
Any help?

Comment from Noronjon
Time May 19, 2010 at 11:42 am

Thanks, works super. No errors, updates exist files, exactly what I need.

Comment from visionary1
Time July 2, 2010 at 4:34 pm

upon request.GetResponse(), it frozed as they say “Patthar ka hogaya”

Comment from anitha
Time August 2, 2010 at 2:15 pm

hi,

I need to upload the document with the attributes but your code writes the contents of the file to the location on document library. Is it possible to upload the file itself?

thanks a bunch for your help!

Comment from scott
Time October 21, 2010 at 8:20 pm

I’m hoping someone can help. I’m getting an error that states “The remote server returned an error: (405) Method Not Allowed”. Has anyone else encountered that error and found a way to resolve it?

Comment from chandra
Time December 16, 2011 at 6:22 pm

I want more details about subfolders document upload issue

Comment from Manjunath
Time March 19, 2012 at 11:27 am

Hello “scott” is your problem resolved?
I am also getting the same error (“The remote server returned an error: (405) Method Not Allowed”) when i use PUT method.

If i use POST method, i am getting 404 error..

Please help me to resolve this.

Comment from Matthew Chestnut
Time April 13, 2012 at 9:35 pm

Exception using SSL on call to request.GetResponse():

The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.

Quick hack, added this right after the “try”:

ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;

Comment from Neil
Time August 24, 2012 at 7:46 am

I am trying to do this in SharePoint 2010 using MS Access. Is there a way to do this using Visual Basic? Thanks!

Comment from bob
Time November 13, 2012 at 4:09 pm

Do you have this code in VBA??? I’m using Microsoft Access to upload to Sharepoint.
thanks
bobh.

Write a comment