Monday, April 11, 2011

Getting file content from the ItemAdding method of SPItemEventReceiver

Today I have spent a lot of time to find the way to get file content (binary data and file name) from the ItemAddingMethod of SPItemEventReceiver. This task is depended with my previous post about content Deploymen. I used event receivers to redirect changes to other site collection and then deploy it to few others site collections. Anyway, I think practice is more interested for you. It is possible to extract files data from HttpContext. You only need to add default constructor, where context will be initialized and get all uploading files from Request.Files property of the context. Be careful, there could be empty files, you need to check ContentLength property firstly. Example is below:

public class DocumentEventReceiver : SPItemEventReceiver {
    
    private HttpContext _context;
    public DocumentEventReceiver () 
    {
        _context = HttpContext.Current;
    }
    
    public override void ItemAdding(SPItemEventProperties properties) 
    {
        HttpFileCollection files = context.Request.Files;
        foreach (String key in files.Keys) 
        {
            if (collection[key].ContentLength > 0) 
            {
               Stream stream = files[key].InputStream;
               string filePath = files[key].FileName;
            }
        }
    }
}
What is about ItemAddingMethod, will ask you? HttpContext doesn't contain any information about changed file content. I use now synchronous ItemAdded receiver and extract file content directly from the item, this is not perfect solution, but I use what I have.
Significant contribution for the first problem was provided by my boss, thanks for him.

2 comments: