Uploading a file into a SharePoint document library with C# code

Here's a small snippet of code to upload a file from the filesystem into a SharePoint document library:

    Stream fStream = File.OpenRead("C:\\Temp\\Filename.pdf");
    byte[] contents = new byte[fStream.Length];

    fStream.Read(contents, 0, (int)fStream.Length);
    fStream.Close();

    SPList list = web.Lists[DocumentLibraryListName];
    Hashtable properties = new Hashtable();
    properties.Add("Title", "This is the title");
    properties.Add("Other_x0020_Properties", "Some other property");

    SPFile destFile = list.RootFolder.Files.Add("Filename.pdf", contents, properties, true);

    if (destFile == null)
    {
        lblError.Text = "<p>Error in adding file. Waiting to re-try.</p>";
    }

There is a free class available named DocLibHelper (search Google to download it) that would help you in uploading files among other things, but if all you need is to upload a document into a SharePoint library, then the above code will do.

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.