Throw exception in contact using aspose api

bool ConvertOlmToPst(string olmFilePath, string fullPstPath)//last
{

    // Create a new PST
    PersonalStorage pst = PersonalStorage.Create(fullPstPath, FileFormatVersion.Unicode);
    var root = pst.RootFolder;

    FolderInfo inboxFolder = pst.CreatePredefinedFolder("Inbox", StandardIpmFolder.Inbox);
    ageDict.Add("Inbox", inboxFolder.ContainerClass);
    FolderInfo sent = pst.CreatePredefinedFolder("Sent Items", StandardIpmFolder.SentItems);
    ageDict.Add("Sent Items", sent.ContainerClass);
    FolderInfo drafts = pst.CreatePredefinedFolder("Drafts", StandardIpmFolder.Drafts);
    ageDict.Add("Drafts", drafts.ContainerClass);
    FolderInfo junk = pst.CreatePredefinedFolder("Junk Email", StandardIpmFolder.JunkEmail);
    ageDict.Add("Junk Email", junk.ContainerClass);
    FolderInfo calendar = root.AddSubFolder("Calendar", "IPF.Appointment");
    ageDict.Add("Calendar", calendar.ContainerClass);
    FolderInfo contacts = root.AddSubFolder("Contacts", "IPF.Contact");
    ageDict.Add("Contacts", contacts.ContainerClass);
    FolderInfo journal = root.AddSubFolder("Journal", "IPF.Journal");
    ageDict.Add("Journal", journal.ContainerClass);
    FolderInfo notes = pst.CreatePredefinedFolder("Notes", StandardIpmFolder.Notes);
    ageDict.Add("Notes", notes.ContainerClass);
    FolderInfo tasks = root.AddSubFolder("Tasks", "IPF.Task");
    ageDict.Add("Tasks", tasks.ContainerClass);
    //Add redifine folder Types//.............................//
    ageDict.Add("Address Book", "IPF.Contact");
    ageDict.Add("Suggested Contacts", "IPF.Contact");

    ageDict.Add("Junk E - mail", "IPF.Note");
    ageDict.Add("Outbox", "IPF.Note");
    ageDict.Add("Deleted Items", "IPF.Note");
    ageDict.Add("All", "IPF.Note");
    ageDict.Add("Follow-Up", "IPF.Note");
    ageDict.Add("Inbox-Categorized1", "IPF.Note");//Suggested Contacts
                                                  //--------------------------------------------------------//

    OlmStorage olm = new OlmStorage(olmFilePath);
    nTotalCount = GetOlmTotalItemCount(olm);
    //nTotalCount = GetTotalItems(olm);
    if (nTotalCount == 0)
    {
        Console.WriteLine("⚠️ No items found in OLM file.");
        return false;
    }

    List<OlmFolder> folders = GetAllOlmFolders(olmFilePath);       
    string Type;
    for (int i = 0; i < folders.Count; i++)
    {
        var folder = folders[i];           
        if (ageDict.TryGetValue(folder.Name, out Type))
        {
            Console.WriteLine($"Alice's age is {Type}");
        }            
        else
        {
            Type = DetectFolderType(olm,folder);
            if (string.IsNullOrEmpty(Type))
            {
                Type = "IPM.Note";
            }
        }          
        if (folder.Name != "Accounts")
        {
            FolderInfo folderfull = EnsureFolderPath(pst, folder.Path, Type);
            try
            {
                try
                {
                    // ✅ Enumerate messages safely
                    var messages = olm.EnumerateMessages(folder);
                    if (messages == null)
                        return false;

                    foreach (MapiMessage mapi in messages) // ✅ Correct type for v25.11
                    {
                        try
                        {
                            if (mapi == null)
                                continue;

                            // ✅ Handle calendar items safely
                            if (mapi.MessageClass.StartsWith("IPM.Appointment", StringComparison.OrdinalIgnoreCase))
                            {
                                var calItem = (MapiCalendar)mapi.ToMapiMessageItem();  // renamed variable

                                // Sanitize invalid dates
                                if (calItem.StartDate < new DateTime(1900, 1, 1))
                                    calItem.StartDate = DateTime.Now;

                                if (calItem.EndDate < new DateTime(1900, 1, 1) || calItem.EndDate < calItem.StartDate)
                                    calItem.EndDate = calItem.StartDate.AddHours(1);

                                folderfull.AddMapiMessageItem(calItem);
                            }
                            else if (mapi.MessageClass.StartsWith("IPM.Contact", StringComparison.OrdinalIgnoreCase))
                            {
                                var contactItem = (MapiContact)mapi.ToMapiMessageItem();                                   
                                try
                                {                                        
                                    folderfull.AddMapiMessageItem(contactItem);                                      
                                }
                                catch (Exception ex1)
                                {
                                   Console.WriteLine($"⚠️ Skipped message in folder {folder.Name}: {ex1.Message}");
                                }
                            }

                            else if (mapi.MessageClass.StartsWith("IPM.Task", StringComparison.OrdinalIgnoreCase))
                            {
                                var task = (MapiTask)mapi.ToMapiMessageItem();
                                folderfull.AddMapiMessageItem(task);
                            }
                            else if (mapi.MessageClass.StartsWith("IPM.StickyNote", StringComparison.OrdinalIgnoreCase))
                            {
                                var note = (MapiNote)mapi.ToMapiMessageItem();
                                folderfull.AddMapiMessageItem(note);
                            }
                            else if (mapi.MessageClass.StartsWith("IPM.Activity", StringComparison.OrdinalIgnoreCase))
                            {
                                var journalItem = (MapiJournal)mapi.ToMapiMessageItem();
                                folderfull.AddMapiMessageItem(journalItem);
                            }
                            else
                            {
                                folderfull.AddMessage(mapi);
                                                                
                            }

                            totalMessageCount++;
                            if (nTotalCount > 0)
                                progress.Progress = (int)((totalMessageCount * 100) / nTotalCount);

                            WriteProgress();
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine($"⚠️ Skipped message in folder {folder.Name}: {ex.Message}");
                        }
                    }                        
                }
                catch (Exception ex)
                {
                    Console.WriteLine("ConvertOstToPst Exception: " + ex.Message);
                    UpdateProgress("Error");
                }
               
            }

            catch (Exception ey)
            {
               Console.WriteLine("ConvertOstToPst Exception: " + ey.Message);
                
            }
            Console.WriteLine($"Folder {i}: {folder.Name}");
            Console.WriteLine($"Folder {i}: {folder.Path}");
        }
    }
    // ✅ Calculate final PST size
    if (File.Exists(fullPstPath))
    {
        FileInfo pstInfo = new FileInfo(fullPstPath);
        double sizeInMB = pstInfo.Length / (1024.0 * 1024.0);
        progress.Convertedpstsize = $"{sizeInMB:F2} MB";
       
    }
    else
    {
        progress.Convertedpstsize = "0.00 MB";
    }
    pst.Dispose();
    Console.WriteLine($" Conversion complete: {totalMessageCount} items processed.");
    
    Console.WriteLine($"Total folders found: {folders.Count}");      
    return true;
}

The “Not a valid Win32 FileTime” exception is thrown by Aspose.Email when a contact contains a DateTime value that cannot be represented as a Win32 FILETIME (the valid range is 01‑01‑1601 to 31‑12‑9999). The library validates these fields when a contact is materialised, and an out‑of‑range or corrupted value causes the exception.

@Anjali12

:white_check_mark: What is causing “Not a valid Win32 FileTime”?

Aspose.Email for .NET validates every DateTime that is stored in a MAPI property before the item is written to a PST/OST file.
The underlying MAPI format stores dates as a Win32 FILETIME value, whose supported range is:

Minimum Maximum
01‑Jan‑1601 00:00:00 31‑Dec‑9999 23:59:59

If any contact field (e.g., Birthday, Anniversary, LastModificationTime, CreationTime, custom date properties, etc.) contains a value outside of this range, Aspose.Email throws the “Not a valid Win32 FileTime” exception.


:hammer_and_wrench: How to handle the exception in your conversion routine

Below are the recommended steps you can add to the ConvertOlmToPst method (or to a helper routine) to make the conversion robust.

:one: Define the allowed FILETIME window once

// FILETIME valid range for MAPI
private static readonly DateTime FileTimeMin = new DateTime(1601, 1, 1, 0, 0, 0, DateTimeKind.Utc);
private static readonly DateTime FileTimeMax = new DateTime(9999, 12, 31, 23, 59, 59, DateTimeKind.Utc);

:two: Sanitize every DateTime property of MapiContact

Create a helper that checks a DateTime? value and replaces it with a safe default (or null) when it is out of range.

private static DateTime? GetSafeDateTime(DateTime? value)
{
    if (!value.HasValue) return null;

    // Convert to UTC because FILETIME is always stored as UTC
    DateTime utc = value.Value.ToUniversalTime();

    if (utc < FileTimeMin || utc > FileTimeMax)
        return null;               // or return FileTimeMin / any fallback you prefer

    return utc;
}

:three: Apply the sanitizer right before adding the contact to the PST

else if (mapi.MessageClass.StartsWith("IPM.Contact", StringComparison.OrdinalIgnoreCase))
{
    var contactItem = (MapiContact)mapi.ToMapiMessageItem();

    // ---- SANITIZE DATE/TIME FIELDS ----
    contactItem.Birthday          = GetSafeDateTime(contactItem.Birthday);
    contactItem.WeddingAnniversary = GetSafeDateTime(contactItem.WeddingAnniversary);
    contactItem.CreationTime      = GetSafeDateTime(contactItem.CreationTime);
    contactItem.LastModificationTime = GetSafeDateTime(contactItem.LastModificationTime);
    // Add any custom date properties you may have:
    // contactItem.SetProperty("MyCustomDate", GetSafeDateTime(customDate));

    try
    {
        folderfull.AddMapiMessageItem(contactItem);
    }
    catch (Exception ex)
    {
        // Log and continue – this ensures a single corrupt contact does not stop the whole conversion.
        Console.WriteLine($"⚠️ Skipped contact in folder {folder.Name}: {ex.Message}");
    }
}

:four: Optional: Global try / catch around the entire folder processing

If you want one‑line protection for any unexpected MAPI issue (including date problems you might have missed):

try
{
    folderfull.AddMapiMessageItem(contactItem);
}
catch (Aspose.Email.FileFormats.Pst.Except.FileTimeOutOfRangeException ftEx)
{
    Console.WriteLine($"⚠️ Date out of range in folder {folder.Name}: {ftEx.Message}");
    // You may decide to skip the item, set a default date, or log it for later analysis.
}
catch (Exception ex)
{
    Console.WriteLine($"⚠️ Unexpected error while adding item to folder {folder.Name}: {ex.Message}");
}

:books: Relevant Aspose.Email Documentation


:rocket: Quick Checklist before running the conversion again

  1. Add the sanitizer (GetSafeDateTime) – guarantees all date fields are inside the FILETIME range.
  2. Wrap AddMapiMessageItem in a try/catch – prevents a single bad contact from aborting the whole PST creation.
  3. Verify the OLM source – if you have many contacts with wrong dates, consider cleaning the source file (e.g., with a script that rewrites dates to a valid placeholder).
  4. Run the conversion on a test folder first – confirm that the exception no longer appears and that the resulting PST opens correctly in Outlook/Windows Mail.

:raising_hand_man: Need further assistance?

If you still encounter issues after applying the above fixes, please provide:

  • A sample OLM file (or a minimal excerpt) that reproduces the error.
  • The exact stack trace of the exception (when possible).

With that information we can pinpoint the problematic property and suggest a more targeted workaround.

Happy coding! :rocket:

this not working

else if (mapi.MessageClass.StartsWith(“IPM.Contact”, StringComparison.OrdinalIgnoreCase))
{
var contactItem = (MapiContact)mapi.ToMapiMessageItem();

// ---- SANITIZE DATE/TIME FIELDS ----
contactItem.Birthday          = GetSafeDateTime(contactItem.Birthday);
contactItem.WeddingAnniversary = GetSafeDateTime(contactItem.WeddingAnniversary);
contactItem.CreationTime      = GetSafeDateTime(contactItem.CreationTime);
contactItem.LastModificationTime = GetSafeDateTime(contactItem.LastModificationTime);
// Add any custom date properties you may have:
// contactItem.SetProperty("MyCustomDate", GetSafeDateTime(customDate));

try
{
    folderfull.AddMapiMessageItem(contactItem);
}
catch (Exception ex)
{
    // Log and continue – this ensures a single corrupt contact does not stop the whole conversion.
    Console.WriteLine($"⚠️ Skipped contact in folder {folder.Name}: {ex.Message}");
}

}

The “Not a valid Win32 FileTime” error happens when a contact in the OLM file has a date outside the range Windows can handle (01‑01‑1601 to 31‑12‑9999). Aspose.Email throws this exception when it encounters such invalid dates. To fix it, you can check each date before adding the contact and replace any out-of-range values with a safe default like DateTime.Now. The same approach can be applied to tasks, calendar items, or notes to ensure the conversion completes without errors.

@Anjali12,

Since MapiContact doesn’t have a direct Birthday property, your issue remains unclear.
Can you provide additional details, e.g. error/stack trace?