Navigating OLM Folders
An OLM file organizes its data into a tree of folders, each represented by an OlmFolder object. This article shows how to enumerate the folder hierarchy, retrieve a specific folder by name, navigate sub-folders, and read folder paths.
Retrieve the Folder Hierarchy
Once a file is open, access its directory structure through the FolderHierarchy property. This property returns a list of OlmFolder objects, each representing a top-level directory in the OLM file. To explore deeper, read the SubFolders property of each folder, which returns its sub-directories. Using these two members you can walk the entire hierarchy.
The example below prints all folders in hierarchical order:
using (var olm = new OlmStorage(fileName))
{
PrintAllFolders(olm.FolderHierarchy, string.Empty);
}
private void PrintAllFolders(IEnumerable<OlmFolder> folderHierarchy, string indent)
{
foreach (var folder in folderHierarchy)
{
Console.WriteLine($"{indent}{folder.Name}");
PrintAllFolders(folder.SubFolders, indent + "-");
}
}
FolderHierarchy and the FromFile Method
The way you open the file affects how FolderHierarchy behaves:
- When you open the file with the constructor, the FolderHierarchy property is initialized automatically.
- When you open the file with the FromFile method,
FolderHierarchyis not initialized by default and returnsnull. In this case, call the GetFolders method explicitly to initialize the hierarchy and retrieve the list of directories:
using (var olm = OlmStorage.FromFile(fileName))
{
var folders = olm.GetFolders();
}
Get a Folder by Name
To retrieve a single folder by name, call the GetFolder method. Pass the folder name as the first argument and a boolean as the second argument that indicates whether case should be ignored during the search.
using (var olm = OlmStorage.FromFile(fileName))
{
// get the Inbox folder by name, ignoring case
OlmFolder folder = olm.GetFolder("Inbox", true);
}
Get a Sub-folder by Name
Each OlmFolder also lets you locate a child folder directly with the GetSubFolder method. Pass the sub-folder name and whether case should be ignored. This is useful when you already hold a parent folder and want to drill down without re-scanning the whole hierarchy.
using (var olm = OlmStorage.FromFile(fileName))
{
OlmFolder inbox = olm.GetFolder("Inbox", true);
// get a sub-folder of Inbox by name
OlmFolder archive = inbox.GetSubFolder("Archive", true);
if (archive != null)
{
Console.WriteLine($"Found sub-folder: {archive.Name}");
}
}
Retrieve Folder Paths
You can read the full path of any folder through the OlmFolder.Path property. The following snippet prints the path of every folder in the file:
using (var storage = new OlmStorage("SampleOLM.olm"))
{
PrintPath(storage.FolderHierarchy);
}
public static void PrintPath(IEnumerable<OlmFolder> folders)
{
foreach (OlmFolder folder in folders)
{
// print the current folder path
Console.WriteLine(folder.Path);
PrintPath(folder.SubFolders);
}
}