Get List Items Using SPQuery
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"]);
topLevelSite = siteCollection.AllWebs[System.Configuration.
ConfigurationManager.AppSettings["TopLevelSite"]];
SPList list = topLevelSite.Lists[System.Configuration.
ConfigurationManager.AppSettings["ListName"]];
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();
}
}