/// <summary>
/// Asynchronous event occurs after the attachment is added
/// </summary>
/// <param name="properties"></param>
public override void ItemAttachmentAdded(SPItemEventProperties properties)
{
base.ItemAttachmentAdded(properties);
// Make sure we have at least one attachment (this should never happen, but just in case)
if (properties.ListItem.Attachments.Count == 0)
{
return;
}
// Get a reference to the attachment
SPFile attachment = properties.ListItem.ParentList.RootFolder.SubFolders["Attachments"].SubFolders[properties.ListItemId.ToString()].Files[properties.ListItem.Attachments.Count - 1];
// Get the raw data of the file
byte[] content = attachment.OpenBinary();
// Get the original attachment name
string originalFileName = attachment.Name;
// Get the new file name with the date/time stamp
string newFileName = GetFileNameWithDate(originalFileName);
// Turn off events so that we don't get an infinite loop when we add back the attachment
DisableEventFiring();
// Delete the original attachment (we can't simply rename the attachment)
properties.ListItem.Attachments.DeleteNow(originalFileName);
// Add the attachment back with the new filename
properties.ListItem.Attachments.AddNow(newFileName, content);
// Turn on events again
EnableEventFiring();
}
/// <summary>
/// Prefix a file name with the current date time
/// </summary>
/// <param name="fileName">The original file name</param>
/// <returns>A file name prefixed with the date time (e.g. 2008010101010101_test.docx)</returns>
private string GetFileNameWithDate(string fileName)
{
DateTime now = DateTime.Now;
return
now.Year.ToString() +
now.Month.ToString().PadLeft(2, '0') +
now.Day.ToString().PadLeft(2, '0') +
now.Hour.ToString().PadLeft(2, '0') +
now.Minute.ToString().PadLeft(2, '0') +
now.Second.ToString().PadLeft(2, '0') +
now.Millisecond.ToString().PadLeft(2, '0') +
"_" + fileName;
}
}