How to upload document in SharePoint document library programmatically

Below is the code for uploading the selected file with custom properties.

SPSecurity.RunWithElevatedPrivileges(delegate()
{

if (fldFile.PostedFile != null)
{
if (fldFile.PostedFile.ContentLength > 0)
{

using (SPSite site = new SPSite(SPContext.Current.Web.Url))
{
using (SPWeb web = site.OpenWeb())
{

Stream fStream = fldFile.PostedFile.InputStream;

byte[] byt = new byte[Convert.ToInt32(fldFile.PostedFile.ContentLength)];
fStream.Read(byt, 0, Convert.ToInt32(fldFile.PostedFile.ContentLength));
fStream.Close();
SPList lst = web.Lists[“Staging Area Zone”];//Test Library

SPUser userAuthor = web.EnsureUser(upAuthor.CommaSeparatedAccounts);
string strAuthor = userAuthor.ID.ToString() + “;#” + userAuthor.Name;

Hashtable metaData = new Hashtable();
metaData.Add(“Title”, fldFile.FileName);
metaData.Add(“Document_Author”, strAuthor);

web.AllowUnsafeUpdates = true;
SPFile destfile = null;
destfile = lst.RootFolder.Files.Add(fldFile.FileName, byt, metaData, true);
if (destfile == null)
{
lblMsg.Text = “Error in adding file”;
}
else
{
if (destfile.CheckOutType != SPFile.SPCheckOutType.None)
{
destfile.CheckIn(“Programmatically Checked In”);
lblMsg.Text = “File is uploaded successfully”;
lst.Update();
}
}
web.AllowUnsafeUpdates = false;
}
}
}
}

});

Advertisements

3 thoughts on “How to upload document in SharePoint document library programmatically

  1. I would like to thank you for the efforts you’ve put in writing this site.

    I’m hoping to view the same high-grade content from you in the future as well.
    In truth, your creative writing abilities has encouraged me to
    get my very own blog now šŸ˜‰

  2. This may be a good product for weight loss but there are many negative feedbacks and
    comments about this product. One of the great things about hoodia iis the lack of negative side effects.
    These people try to find out many different ways to lose their body’s weight
    and get easily motivated by different weight loss methods
    which offer attractive weight loss.

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s