SharePoint Blogs / SharePoint University
SharePoint Blogs and SharePoint University - all in one place!
Need SharePoint Training? Attend a SharePoint Bootcamp!

Please delete cookies related to sharepointblogs.com and sharepointu.com to resolve login issues!

Event Handler for Renaming List Item Attachments

I needed the ability to rename list item attachments automatically as attachments were uploaded. I wanted to prefix the filename with the current date/time so that 1) all files would have a unique filename and 2) the files would be sorted in the Display form for the item.

I created an event handler for the ItemAttachmentAdded event. It turns out that in the ItemAttachment... events, you cannot modify the attachment file in any way, including renaming it. The BeforeUrl and After Url properties are read-only, and there is no SPListItem in the SPItemEventProperties object to use. The only handle you can get to the actual file is to traverse the Attachments folder of the list until you get a reference to the actual SPFile object that represents the attachment. The SPFile object has only ReadOnly properties for Title/Name, so you cannot do anything there.

The only way I could find to perform a rename, was to get the binary Byte[] array of the file, create a new attachment with the proper file name, and then delete the original attachment. My code is below:

/// <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;
 
}
 
    }

This had another benefit, in that it made the attachment file names pretty much unique. Unlike documents in doc libraries, new attachments with the same file name as an existing attachment will not override the original, and the user will see an error message from SharePoint when trying to upload the attachment. This gets around that unfriendly experience.

To register my attachment, I used Gary Lapointe's custom stsadm command, AddEventReceiver.


Posted 12-18-2008 8:57 AM by adamtoth

Comments

Links (12/18/2008) « Steve Pietrek - Everything SharePoint wrote Links (12/18/2008) &laquo; Steve Pietrek - Everything SharePoint
on 12-18-2008 7:34 PM

Pingback from  Links (12/18/2008) &laquo; Steve Pietrek - Everything SharePoint

Admin's Blog wrote Hot links - 3rd Week of December 2008
on 01-26-2009 4:27 AM

How my team does agile ( Link ) My SharePoint Development Best Practices ( Link ) SharePoint workflow

Add a Comment

(required)  
(optional)
(required)  
Remember Me?
Need SharePoint Training? Attend a SharePoint Bootcamp!
Posts (c) their respective authors. Everything else (c) 2009 SharePoint Experts, Inc.