Sharepoint Insight by Namwar Rizvi

Sharepoint Tips, Tricks and inside knowledge from real world experience by Namwar Rizvi

Programmatically upload a file to Document Library

Posted by namwar on January 10, 2009


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;

    }

Advertisements

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

  1. DuFFeR said

    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. SG said

    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. ab said

    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. Sandeep said

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

  5. sona1 said

    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. joeygUrL said

    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. bhuvan said

    Thanks for the post! Helped me a lot.

  8. dishashah08 said

    Hey

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

  9. Anu said

    I m geeting error unable to connect to remote server.

  10. Elona said

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

  11. Noronjon said

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

  12. visionary1 said

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: