Quantcast
Channel: Exchange Server Development forum
Viewing all articles
Browse latest Browse all 7132

Exchange Web Services (EWS) - InvalidCastException

$
0
0

I have a service that reads the new emails in an Office 365 Exchange mailbox, and saves attachments in a directory.

For most emails it runs well, however I'm getting a lot of the following exceptions lately:

System.InvalidCastException: Unable to cast object of type 'Microsoft.Exchange.WebServices.Data.ItemAttachment' to type 'Microsoft.Exchange.WebServices.Data.FileAttachment'

I will post a piece of my code, could anyone please have a look and tell me what I need to change? It's .NET 4.0, Visual Studio 2010, Visual Basic and the latest Exchange Web Services api, 2.2.

Dim sf As SearchFilter = New SearchFilter.SearchFilterCollection(LogicalOperator.And, New SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, False))
Dim findResults As FindItemsResults(Of Item) = service.FindItems(WellKnownFolderName.Inbox, sf, New ItemView(128))

If findResults.Count > 0 Then
	Dim items As ServiceResponseCollection(Of GetItemResponse) =
		service.BindToItems(findResults.Select(Function(item) item.Id),
		   New PropertySet(BasePropertySet.FirstClassProperties, EmailMessageSchema.From, EmailMessageSchema.Sender, EmailMessageSchema.ToRecipients, EmailMessageSchema.IsRead))

	For Each itItem As Microsoft.Exchange.WebServices.Data.Item In findResults.Items

		If TypeOf itItem Is EmailMessage Then

			Dim mailItem As EmailMessage = DirectCast(itItem, EmailMessage)

			If itItem.HasAttachments Then
				itItem.Load()
				For Each Attachment In itItem.Attachments
					If TypeOf Attachment Is FileAttachment Then
						Dim fa As FileAttachment = itItem.Attachments(0)
						pathAttachment = "c:\temp\" & fa.name 'not actual code, but to make this code readable and to the point
						Try
							fa.Load(pathAttachment) 'save file


Viewing all articles
Browse latest Browse all 7132

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>