Moved ensureDirectoryExists to avoid code duplication.