views:

567

answers:

4

I would expect something like this to work but the ListItem, BeforeProperties, AfterProperties are all null/empty. I need the file name and file content.

public class MyItemEventReceiver : SPItemEventReceiver {
    public MyItemEventReceiver() {}
    public override void ItemAdding(SPItemEventProperties properties) {
        SPListItem item = properties.ListItem;
        bool fail = item.File.Name.Equals("fail.txt");
        if (fail) {
            properties.ErrorMessage = "The file failed validation";
            properties.Cancel = true;
        }
    }
}

I can't use ItemAdded as it is asynchronous and I need to be synchronous, I may prevent the upload and display a message to the user.

Any suggestions would be appreciated. For example, is it possible to override the Upload.aspx?

A: 

Notice the suffix -"adding." It's going to be null because it wasn't added yet. Try using -"added."

EDIT: I believe there's an "AfterProperties rather than properties object you can grab somewhere, i'm out the door at the moment, but i'm sure you can do some digging on google to find the related method getting thrown.

Janie
+1  A: 

As Janie wrote this event is triggered before the insert, but you should be able to access the BeforeProperties so you don't have the use the ItemAdded event.

That would in most cases be to late as the ItemAdding event is commonly used to validate the input.

Happy coding

Kasper
A: 

It is possible to retrieve the filename by using a property (there are a few you can use). SPItemEventProperties.BeforeUrl contains this.

It is not possible to retrieve the contents of the file as this is not provided by any member of SPItemEventProperties. The file has not been written to the database yet and exists only in the memory of the server the user is connected to. Therefore unfortunately standard methods cannot be used.

Alex Angas
+1  A: 

You can use the HttpContext to retrieve the HttpFileCollection which should contain the uploaded files. This will only work for individual file uploads through the web UI. Doing multiple file uploads, or saving directly from Office won't create an HttpContext. Try something like this:

private HttpContext context;

public MyItemEventReceiver() {
    context = HttpContext.Current;
}

public override void ItemAdding(SPItemEventProperties properties) {
    HttpFileCollection collection = context.Request.Files;
    foreach (String name in collection.Keys) {
     if (collection[name].ContentLength > 0) {
      // Do what you need with collection[name].InputStream
     }
    }
}
Matt Donald