Friday 13 June 2014

Upload a File to List Using SPQuery with out List ID(Using another Identity)

public void UploadFile(string strTitle, HttpPostedFile filename)
{
WindowsIdentity objWindowsIdentity = WindowsIdentity.GetCurrent();
WindowsImpersonationContext objWindowsImpersonationContext = null;
RevertToSelf();
SPQuery oquery = null;
SPSite siteCollection = null;
SPWeb topLevelSite = null;
SPListItemCollection myitems = null;
try
{
objWindowsImpersonationContext = WindowsIdentity.GetCurrent().Impersonate();
siteCollection = new SPSite(System.Configuration.ConfigurationManager.AppSettings["SPDocumentLibrary"]);//http://SERVER:PORT/
topLevelSite = siteCollection.AllWebs[System.Configuration.ConfigurationManager.AppSettings["TopLevelSite"]];//Null
SPList list = topLevelSite.Lists[System.Configuration.ConfigurationManager.AppSettings["ListName"]];//LIST NAME
topLevelSite.AllowUnsafeUpdates = true;
//Create an instance of SPQuery Object
oquery = new SPQuery();
//Specify the condition
oquery.Query = "" + strTitle.ToString().Trim() + "";
//Set the row limit
oquery.RowLimit = 1;
//Assign the query object to myitems List Collection
myitems = list.GetItems(oquery);
foreach (SPListItem item in myitems)
{
byte[] bufDoc = null;
int nLen = filename.ContentLength;
bufDoc = new byte[nLen];
Stream oStream = filename.InputStream;
oStream.Read(bufDoc, 0, nLen);
SPList DocumentLibrary = topLevelSite.Lists[System.Configuration.ConfigurationManager.AppSettings["ListName"]];
item.Attachments.Add(System.IO.Path.GetFileName(filename.FileName.ToString()), bufDoc);
item.Update();
break;
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
objWindowsImpersonationContext.Undo();
topLevelSite.AllowUnsafeUpdates = false;
siteCollection.Dispose();
topLevelSite.Dispose();
}
}