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
public class DocLibActivities : WebPart

FileUpload oFileUploader;
protected override void CreateChildControls()
oFileUploader = new FileUpload();

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);
SPFile oSPNewFile = objTargetFolder.Files.Add(strFilename, fbytes, true);

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



1 comment:

Cindy Dy said...

You are an awesome blogger. This is one of the best blog I had visited so far. Hope to read more post from you in the future. Keep it up. God bless.