Splitting and Merging PST files

Splitting and Merging PST files

A PST file that keeps growing becomes slow to open, hard to back up and may hit the size limit of older Outlook versions. Aspose.Email for C++ can cut such a storage into several smaller ones and, the other way round, combine several storages into one. Both operations work on the files directly, without Outlook, and report their progress through events.

The samples in this article use these headers and namespaces:

#include <Mapi/MapiMessage.h>
#include <Storage/Pst/PersonalStorage.h>
#include <Storage/Pst/FolderInfo.h>
#include <Storage/Pst/FileFormatVersion.h>
#include <Storage/Pst/ItemMovedEventArgs.h>
#include <Storage/Pst/StorageProcessedEventArgs.h>
#include <Storage/Pst/StorageProcessingEventArgs.h>
#include <Storage/Pst/MessageStore.h>
#include <Storage/Pst/PersonalStorageQueryBuilder.h>
#include <Tools/Search/MailQuery.h>
#include <Tools/Search/StringComparisonField.h>
#include <system/array.h>
#include <system/convert.h>
#include <system/collections/list.h>
#include <system/io/directory.h>
#include <system/io/path.h>

using namespace System;
using namespace Aspose::Email;
using namespace Aspose::Email::Storage::Pst;
using namespace Aspose::Email::Tools::Search;

Splitting into multiple PSTs

PersonalStorage::SplitInto distributes the content of a storage over new PST files of roughly the given size, in bytes, and writes them into the given directory. Each part keeps the folder structure of the source, and the source file is not modified, so it can be opened read-only. Existing part files are not overwritten - the call fails instead - so the target directory should be empty.

// SplitInto does not overwrite the parts of an earlier run, so start with an empty directory
if (IO::Directory::Exists(u"Parts"))
{
    IO::Directory::Delete(u"Parts", true);
}
IO::Directory::CreateDirectory_(u"Parts");

auto pst = PersonalStorage::FromFile(u"demo.pst", false);

// parts of about 5 MB each
pst->SplitInto(static_cast<int64_t>(5000000), u"Parts");
pst->Dispose();

for (String file : IO::Directory::GetFiles(u"Parts", u"*.pst"))
{
    Console::WriteLine(u"Part written: " + IO::Path::GetFileName(file));
}

Naming the Parts and Following the Progress

The overload SplitInto(chunkSize, partFileNamePrefix, path) controls how the parts are named. Each file is called {prefix}part{number}.pst; when the prefix is empty the display name of the source storage takes its place, which gives names such as Personal folders_part0.pst.

Two events report what the operation is doing. StorageProcessing is raised before a part is written and StorageProcessed once it is finished; the second one also hands over the finished storage through StorageProcessedEventArgs::Chunk, so a part can be inspected without opening its file again. The same events fire while MergeWith reads the storages it merges.

if (IO::Directory::Exists(u"PartsBySize"))
{
    IO::Directory::Delete(u"PartsBySize", true);
}
IO::Directory::CreateDirectory_(u"PartsBySize");

auto pst = PersonalStorage::FromFile(u"demo.pst", false);

// raised before a part is started
pst->StorageProcessing.connect(
    std::function<void(System::SharedPtr<System::Object>, System::SharedPtr<StorageProcessingEventArgs>)>(
        [](System::SharedPtr<System::Object> sender, System::SharedPtr<StorageProcessingEventArgs> e)
        {
            Console::WriteLine(u"Writing " + e->get_FileName());
        }));

// raised when a part is complete; Chunk gives access to the storage that was just written
pst->StorageProcessed.connect(
    std::function<void(System::SharedPtr<System::Object>, System::SharedPtr<StorageProcessedEventArgs>)>(
        [](System::SharedPtr<System::Object> sender, System::SharedPtr<StorageProcessedEventArgs> e)
        {
            Console::WriteLine(u"Finished " + e->get_FileName() + u", items: " +
                Convert::ToString(e->get_Chunk()->get_Store()->GetTotalItemsCount()));
        }));

pst->SplitInto(static_cast<int64_t>(5000000), u"chunk_", u"PartsBySize");
pst->Dispose();

Splitting by Criterion

Size is not the only way to cut a storage apart. SplitInto(criteria, path) takes a list of queries instead of a size and writes one part per query, holding the messages that match it. A message that matches none of the queries is left out of every part, so the criteria double as a filter - a convenient way to pull one sender, one date range or one folder out of a large mailbox.

The parts keep the folder structure of the source, and the source file itself is not modified.

if (IO::Directory::Exists(u"PartsByCriteria"))
{
    IO::Directory::Delete(u"PartsByCriteria", true);
}
IO::Directory::CreateDirectory_(u"PartsByCriteria");

// one query per part; a message that matches none of them is not copied anywhere
auto criteria = System::MakeObject<System::Collections::Generic::List<System::SharedPtr<MailQuery>>>();

auto firstSender = System::MakeObject<PersonalStorageQueryBuilder>();
firstSender->get_From()->Contains(u"erin@example.com", true);
criteria->Add(firstSender->GetQuery());

auto secondSender = System::MakeObject<PersonalStorageQueryBuilder>();
secondSender->get_From()->Contains(u"frank@example.com", true);
criteria->Add(secondSender->GetQuery());

auto pst = PersonalStorage::FromFile(u"source.pst", false);
pst->SplitInto(criteria, u"PartsByCriteria");
pst->Dispose();

for (String file : IO::Directory::GetFiles(u"PartsByCriteria", u"*.pst"))
{
    Console::WriteLine(IO::Path::GetFileName(file));
}

Merging into a single PST

PersonalStorage::MergeWith takes an array of file paths and copies the content of each of those storages into the one it is called on, which therefore has to be opened writable. Folders with the same path are combined into one, and folders that exist in only one of the storages are added with their whole subtree. The StorageProcessed event reports each source file once it has been read.

auto merged = PersonalStorage::Create(u"Merged.pst", FileFormatVersion::Unicode);

merged->StorageProcessed.connect(
    std::function<void(System::SharedPtr<System::Object>, System::SharedPtr<StorageProcessedEventArgs>)>(
        [](System::SharedPtr<System::Object> sender, System::SharedPtr<StorageProcessedEventArgs> e)
        {
            Console::WriteLine(u"Merged " + IO::Path::GetFileName(e->get_FileName()));
        }));

merged->MergeWith(System::MakeArray<String>({u"demo.pst", u"source.pst"}));

Console::WriteLine(u"Items in the merged storage: " + Convert::ToString(merged->get_Store()->GetTotalItemsCount()));
merged->Dispose();

Merging Folders from another PST

FolderInfo::MergeWith copies a single folder, with everything below it, from another storage into the folder it is called on. Unlike PersonalStorage::MergeWith, which takes whole files, this lets you pick what to bring over and where to put it.

Both storages stay open during the operation: the source is only read, so it may be opened read-only, while the destination has to be writable. The ItemMoved event of the destination folder reports each item as it arrives, and ItemMovedEventArgs tells messages and folders apart.

auto destination = PersonalStorage::FromFile(u"demo.pst", true);
auto source = PersonalStorage::FromFile(u"source.pst", false);

auto target = destination->get_RootFolder()->AddSubFolder(u"FolderFromAnotherPst");
auto imported = source->get_RootFolder()->GetSubFolder(u"Imported");

// optional: report every item as it arrives
target->ItemMoved.connect(
    std::function<void(System::SharedPtr<System::Object>, System::SharedPtr<ItemMovedEventArgs>)>(
        [](System::SharedPtr<System::Object> sender, System::SharedPtr<ItemMovedEventArgs> e)
        {
            Console::WriteLine(u"Merged an item, message: " + Convert::ToString(e->get_IsMessage()) +
                u", folder: " + Convert::ToString(e->get_IsFolder()));
        }));

// the source folder and its whole subtree are copied into the target folder
target->MergeWith(imported);

Console::WriteLine(u"The merged folder holds " +
    Convert::ToString(destination->get_RootFolder()->GetSubFolder(u"FolderFromAnotherPst")->get_ContentCount()) +
    u" messages");

source->Dispose();
destination->Dispose();

The second overload, MergeWith(sourceFolder, recursiveHandler), decides whether the ItemMoved event is also raised for the items of the subfolders that come with the source folder.