1

How to get the name of the file being uploaded if the listitem is not created yet?

public override void ItemAdding(SPItemEventProperties properties)
{
    SPWeb TargetWeb = properties.OpenWeb();

    //SPListItem item = properties.ListItem; <------ ERROR
    //SPFile document = item.File; <------ ERROR 
}
1
  • For reference, you get the errors you stated because the file nor the item exists yet in the content database because the Add operation hasn't yet been completed. Why are the properties even there, then? Lazy developers, same object (SPItemEventProperties) is used across all event receivers.
    – James Love
    Commented Jan 6, 2014 at 14:27

4 Answers 4

3

You can use Properties.AfterUrl and then split it by "/" and get the last part of string to get document Name. Link to source

1

do instead:

 //get the url for the file name
 string fileName = properties.AfterUrl;
 //split it when it gets to /
 string[] nFileName = url.Split('/')
 //return only the file name
 fileName = nFileName[1];

as for whay its returning an error its stated in msdn! The file your trying to get is not in the DB on item adding and so will return a null reference object ;), if you need to use SPFile document = properties.ListItem.File; than that needs to be done within the item added not adding!

A File object that represents the file. If the item does not exist, if the item is a folder, or if the item is not located in a document library, the File property returns an Object whose ServerObjectIsNull property is true.

http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.client.listitem.file.aspx

0

got it working with the below

//Files
string itemName = properties.Web.GetFile(properties.AfterUrl).Name;

//Folders
string itemName = properties.Web.GetFolder(properties.AfterUrl).Name;
-1
properties.AfterProperties["Internal Name of the column"];

you should go through this article:

Working with BeforeProperties and AfterProperties on SPItemEventReceiver - Blog http://www.synergyonline.com/Blog/Lists/Posts/Post.aspx?ID=122

It will help you better understand what is going on in Event Receivers.

1
  • string tste = properties.AfterProperties["fimename"]; ???
    – JulianoG
    Commented Jan 6, 2014 at 14:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.