2017-02-13 31 views
2

У меня есть код, который перемещает элементы в почтовую папку из удаленных элементов. Код работает хорошо и перемещает все элементы в целом. Проблема возникает, когда встречается элемент, который не является IPM.Note. Он дает ошибку, которая является нулевой ссылкой (см.: What is a NullReferenceException, and how do I fix it?)EWS FindItemsResults <Item> Item.Move() не перемещает определенные типы элементов в папку Mail, такую ​​как IPM.Appointment

Что странно, поскольку там есть элементы, и оно не может быть нулевым.

Вот фрагмент кода:

// Specify the Exchange Service 
ExchangeService E_SERVICE = new ExchangeService(ExchangeVersion.Exchange2010_SP2); 

// Look at the root of the Mailbox (Top of Information Store) 
FolderId fldr_id = WellKnownFolderName.MsgFolderRoot; 

// Define the folder view 
FolderView newFV = new FolderView(1000); 

// Perform a deep traversal 
newFV.Traversal = FolderTraversal.Deep; 

// Get the results of all the folders in the Mailbox 
FindFoldersResults f_results = E_SERVICE.FindFolders(fldr_id, newFV); 

// Define the source and target folder id variables as null. 
FolderId src_fldr_id = null; 
FolderId tgt_fldr_id = null; 

// Define the folders we are looking to move items from the source to the target 
string source = "Deleted Items" 
string target = "Old Deleted Items" 

// Search through all the folders found in the mailbox 
foreach (Folder fldr in f_results) 
{ 
    // If the source folder name is the same as the current folder name then set the source folder ID 
    if (fldr.DisplayName.ToLower() == source.ToLower()) 
    { 
     src_fldr_id = fldr.Id; 
    } 
    // If the target folder name is the same as the current folder name then set the target folder ID 
    if (fldr.DisplayName.ToLower() == target.ToLower()) 
    { 
     tgt_fldr_id = fldr.Id; 
    } 
} 

// Get all the items in the folder 
FindItemsResults<Item> findResults = E_SERVICE.FindItems(src_fldr_id, new ItemView(1000)); 

// If the number of results does not equal 0 
if (findResults.TotalCount != 0) 
{ 
    // For each item in the folder move it to the target folder located earlier by ID. 
    foreach(Item f_it in findResults) 
    { 
     f_it.Move(tgt_fldr_id); 
    } 
} 

Мы получаем ошибку брошенную на следующей строке:

 f_it.Move(tgt_fldr_id); 

Это как Null Reference Exception, который не может быть так, как есть есть элементы, и это обычно элемент, который не является IPM.Note.

Итак, как мне обойти это и обеспечить, чтобы предмет перемещался независимо от того, какой тип он есть?

Я уже писал здесь об этом Unable to move Mail items of different Item classes from the same folder using EWS

Только сбит об этом будучи NullReferenceException, когда это не так!

Так что любые полезные ответы были бы весьма признательны.

+0

'Folder src_folder = Folder.Bind (E_SERVICE, src_fldr_id);' вы выполняете эту привязку, но не используете ее нигде? –

+0

@CallumLinington извиняюсь, был скопирован случайно. Теперь я исправил это. –

ответ

0

Хорошо подходит, чтобы обойти эту проблему, чтобы убедиться, что вы Load() пункт перед выполнением Move()

убедитесь, что вы используете блок try..catch и обрабатывать исключения, как показано ниже:

try 
{ 
    f_it.Move(tgt_fldr_id); 
} 
catch (Exception e) 
{ 
    Item draft = Item.Bind(E_SERVICE, f_it.Id); 
    draft.Load(); 
    draft.Move(tgt_fldr_id); 
} 

Это заставит элемент загружаться отдельно, а затем перемещать его, даже если он вызывает ошибку. Почему, это пока неизвестно. Но, надеюсь, вам помогут те, кто борется с тем, почему вы получаете NullReferenceException

Спасибо всем!

EDIT: Возможно, вы захотите прочитать https://social.msdn.microsoft.com/Forums/exchange/en-US/b09766cc-9d30-42aa-9cd3-5cf75e3ceb93/ews-managed-api-msgsender-is-null?forum=exchangesvrdevelopment о том, почему некоторые элементы имеют значение Null, так как это поможет вам справиться с нулевыми элементами, которые вернутся немного лучше.