0

I need to check if attachment already exists:

ListItem item = list.GetItemById(_id);
context.Load(item, l => l.AttachmentFiles);
context.ExecuteQuery();

if (item.AttachmentFiles.Any(x => x.FileName == _filename))
    // do something

This gives me error

The property or field 'FileName' has not been initialized.

How can I initialize FileName property of attachments?

2

You can use the GetByFileName method of the AttachmentFiles to determine whether the attachment exists or not.

Modify your code as below:

ListItem item = list.GetItemById(_id);
context.Load(item, l => l.AttachmentFiles);
context.ExecuteQuery();

try
{
    var attachment = item.AttachmentFiles.GetByFileName(_filename);
    context.Load(attachment);
    context.ExecuteQuery();
}
catch(Exception ex)
{
    // file doesn't exist
    // do something
}

Reference - AttachmentCollection.GetByFileName method

You can also make use of the GetFileByServerRelativeUrl to determine whether file exists or not as below:

string relativeUrl = $"/sites/test/Lists/Custom List/Attachments/{_id}/{_filename}";

try
{
    var file = context.Web.GetFileByServerRelativeUrl(relativeUrl);
    context.Load(file);
    context.ExecuteQuery();
}
catch(Exception ex)
{
    //do something if file not found
}

Reference - Web.GetFileByServerRelativeUrl method

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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