Wednesday, 30 April 2014

Sharepoint Upload Document to Document Library

public bool UploadToMoss(HttpPostedFile filename, string strDocLibraryName, string strDocCategory, string strDocType)
{
WindowsIdentity wi = WindowsIdentity.GetCurrent();
WindowsImpersonationContext ctx = null;
RevertToSelf();
bool blStatus = true;
try
{
ctx = WindowsIdentity.GetCurrent().Impersonate();
SPSite siteCollection = null;
SPWeb topLevelSite = null;
string strDocLibraryLink = System.Configuration.ConfigurationManager.AppSettings["SPDocLibrary"].ToString();
siteCollection = new SPSite(strDocLibraryLink);
topLevelSite = siteCollection.AllWebs[ConfigurationManager.AppSettings["TopLevelSite"].ToString()];
topLevelSite.AllowUnsafeUpdates = true;
SPFolder objFolder = topLevelSite.GetFolder("" + strDocLibraryName + "/" + strDocCategory + "/" + strDocType + "");
byte[] bufDoc = null;
string strFileName = Path.GetFileName(filename.FileName);
int nLen = filename.ContentLength;
bufDoc = new byte[nLen];
Stream oStream = filename.InputStream;
oStream.Read(bufDoc, 0, nLen);
System.GC.AddMemoryPressure(200024);
SPFile file = objFolder.Files.Add(strFileName, oStream, true);
file.Update();
}
catch (Exception ex)
{
blStatus = false;
throw;
}
finally
{
System.GC.RemoveMemoryPressure(200024);
ctx.Undo();
}
return blStatus;
}