Wednesday, June 17, 2015

How to upload document in SharePoint document library programmatically

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;
}
}
}
}
});

No comments:

Post a Comment