Francisco Prado
Francisco Prado

Reputation: 86

How to download specific file attachments on EWS API

this is what I have so far, the thing is with this code i can download all of the attachments found in the message, but what i really need is to download two specific file extension attachment (.PDF and .XML, IE), any tip will be very grateful:

static void Main(string[] args)
    {
        try
        {
            ExchangeService service = new      ExchangeService(ExchangeVersion.Exchange2010_SP2);
            service.Credentials = new NetworkCredential("USR", "PWD", "domain");
            service.AutodiscoverUrl("someone@example.com");

            FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox, new ItemView(int.MaxValue));
            Console.WriteLine("Found " + findResults.TotalCount + " Messages");

                if (findResults != null && findResults.Items != null && findResults.Items.Count > 0)
                    foreach (Item item in findResults.Items)

                    {
                        EmailMessage message = EmailMessage.Bind(service, item.Id, new PropertySet(BasePropertySet.IdOnly, ItemSchema.Attachments, ItemSchema.HasAttachments));
                        foreach (Attachment attachment in message.Attachments)
                        {
                            if (attachment is FileAttachment)
                            if (attachment.Name.Contains(".xml"))
                            {
                                FileAttachment fileAttachment = attachment as FileAttachment;
                                fileAttachment.Load("c:\\folder\\" + fileAttachment.Name);
                                Console.WriteLine("Attachment name: " + fileAttachment.Name);
                            }
                        }
                        Console.WriteLine(item.Subject);
                    }
                else
                    Console.WriteLine("No messages");
        }
        catch (Exception e)
        {

            Console.WriteLine(e.Message);
        }
    }

Upvotes: 3

Views: 5706

Answers (1)

eddie_cat
eddie_cat

Reputation: 2583

Moving the code edit/comment into an answer.

if (attachment is FileAttachment)
{
         if (attachment.Name.EndsWith(".xml") || attachment.Name.EndsWith(".pdf"))
         {
             FileAttachment fileAttachment = attachment as FileAttachment;
             fileAttachment.Load("c:\\folder\\" + fileAttachment.Name);
             Console.WriteLine("Attachment name: " + fileAttachment.Name);
         }
}

The solution was simply to check if the file name contained .xml or .pdf before downloading and ignore all others.

Upvotes: 3

Related Questions