Programmatically upload a file to Document Library

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

19 thoughts on “Programmatically upload a file to Document Library”

  1. 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?

  2. 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.

  3. 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.

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

  5. 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

  6. 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
    }

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

  8. 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!

  9. 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?

  10. 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.

  11. 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;

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

Comments are closed.

Share via
Copy link
Powered by Social Snap