Wednesday, 23 April 2014

Sharepoint Impersonation

Sharepoint Impersonation
public void UploadAttachment(FileUpload txtUploadFile, string ListItemID, string SPSiteURL, string SPTopSiteName, string SPListName)
{
{
SPSite _objSPSite = null;
SPWeb _objSPWeb = null;
SPList _objSPList = null;
SPListItem _objSPListItem = null;
SPAttachmentCollection _objSPAttachmentCollection = null;
HttpPostedFile _objHttpPostedFile = txtUploadFile.PostedFile;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (_objSPSite = new SPSite(SPSiteURL))
{
_objSPWeb = _objSPSite.AllWebs[SPTopSiteName];
_objSPSite.OpenWeb();
}
});
try
{
_objSPList = _objSPWeb.Lists[SPListName];
_objSPWeb.AllowUnsafeUpdates = true;
_objSPListItem = _objSPList.GetItemById(Convert.ToInt32(ListItemID.ToString().Trim()));
_objSPAttachmentCollection = _objSPListItem.Attachments;
if (!string.IsNullOrEmpty(txtUploadFile.PostedFile.FileName.ToString().Trim()))
{
byte[] bufDoc = null;
int nLen = _objHttpPostedFile.ContentLength;
bufDoc = new byte[nLen];
Stream oStream = _objHttpPostedFile.InputStream;
oStream.Read(bufDoc, 0, nLen);
_objSPAttachmentCollection.Add(System.IO.Path.GetFileName(_objHttpPostedFile.FileName.ToString()), bufDoc);
bufDoc = null;
}
_objSPListItem.Update();
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (_objSPWeb != null)
{
_objSPWeb.AllowUnsafeUpdates = false;
_objSPWeb.Dispose();
_objSPWeb = null;
}
if (_objSPSite != null)
{
_objSPSite.Dispose();
_objSPSite = null;
}
_objSPAttachmentCollection = null;
_objSPListItem = null;
_objSPList = null;
}
}
}