Event Handler : Restrict Document Size

using System;
using System.Security.Permissions;
using System.Runtime.InteropServices;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using VSeWSS;
using System.Web;

namespace FileUploadEventHandler
{
[CLSCompliant(false)]
[TargetList(“00bfea71-e717-4e80-aa17-d0c71b360101”)]
[Guid(“2b3a51b5-8087-4506-ad74-40c48d1a348b”)]
public class FileUploadReceiverItemEventReceiver : SPItemEventReceiver
{
///
/// Initializes a new instance of the Microsoft.SharePoint.SPItemEventReceiver class.
///

public FileUploadReceiverItemEventReceiver()
{ }

///
/// Asynchronous after event that occurs after a new item has been added to its containing object.
///
///
/// A Microsoft.SharePoint.SPItemEventProperties object that represents properties of the event handler.
///
public override void ItemAdded(SPItemEventProperties properties)
{
SPWeb web = properties.OpenWeb();
string strFileUrl = properties.AfterUrl;
SPFile file = web.GetFile(strFileUrl);
if (file.Exists)
{
long iFileSize = file.Length;
double iFileSizeinMB = (iFileSize / 1024) / 1024;
if (iFileSize > 2)
{
SPListItem currentItem = properties.ListItem;
currentItem.Delete();
}
}
}

///
/// Synchronous before event that occurs when a new item is added to its containing object.
///
///
/// A Microsoft.SharePoint.SPItemEventProperties object that represents properties of the event handler.
///
public override void ItemAdding(SPItemEventProperties properties)
{
string strFileUrl = properties.BeforeUrl;
string[] arrFileUrl = strFileUrl.Split(‘.’);
if (arrFileUrl.Length > 0)
{
string strFileExt = arrFileUrl[arrFileUrl.Length – 1];
if (strFileExt != “doc” && strFileExt != “docx”)
{
properties.ErrorMessage = “You can only upload doc or docx files in this document library”;
properties.Cancel = true;
}
}

}
}
}

2 comments

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s