Monday, February 28, 2011

WebPart to Upload to sharePoint Document Lib using SharePoint Object Model

//Following code using SharePoint Object Model and Fileupload class.
//It uploads a docuent to 'Shared Documents' document library.


using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace DocLibActivities.DocLibActivities
{
[ToolboxItemAttribute(false)]
public class DocLibActivities : WebPart
{

FileUpload oFileUploader;
protected override void CreateChildControls()
{
oFileUploader = new FileUpload();
this.Controls.Add(oFileUploader);



}
void btnUpload_Click(object sender, EventArgs e)
{

string strFilename = oFileUploader.FileName;
using (SPWeb objThisWeb = SPContext.Current.Web)
{
SPFolder objTargetFolder = objThisWeb.Lists["Shared Documents"].RootFolder;
foreach (SPFile objFile in objTargetFolder.Files)
{
if (Context.Request.InputStream.Length != null)
{

System.IO.Stream oIOStream = Context.Request.InputStream;
byte[] fbytes = new byte[oIOStream.Length];
oIOStream.Read(fbytes, 0, (int)oIOStream.Length);
oIOStream.Close();
SPFile oSPNewFile = objTargetFolder.Files.Add(strFilename, fbytes, true);
oSPNewFile.CheckOut();

}
this.Page.Response.Redirect(objThisWeb.Url + "/" + objTargetFolder.Url);
}
}

}


}
}

No comments: