Saturday, October 25, 2008

Copy Document Library file into local server using event handler

public override void ItemAdded(SPItemEventProperties properties)
{
try
{
//Copy Document Library file into local server using event handler
base.ItemAdded(properties);
DisableEventFiring();

SPWeb web = properties.OpenWeb();
web.AllowUnsafeUpdates = true;
SPList ilist = web.Lists[properties.ListId];

SPFolder folder = web.GetFolder(properties.ListTitle.ToString());

foreach (SPFile x in folder.Files)
{
if (properties.ListItemId == x.Item.ID)
{
string strpath = @"D:/Trushar/" + folder.Name.ToString() + "/" + x.Name.ToString();
//FileStream fs = new FileStream(@"D:/Trushar/MyDoc/Test1.jpg", FileMode.Create);
FileStream fs = new FileStream(strpath, FileMode.Create);
BinaryWriter binaryWriter = new BinaryWriter(fs);
byte[] fileData = (byte[])x.OpenBinary();

binaryWriter.Write(fileData);
binaryWriter.Close();
break;
}
}

EnableEventFiring();

}
catch (Exception ex )
{


}




}