この例では、フォルダー パスを取得して関連するフォルダーを取得します。
例
注:
次のコード サンプルは、『Programming Applications for Microsoft Office Outlook 2007』からの抜粋です。
次のコード例では、GetKeyContacts メソッドは GetRootFolder() プロパティを使用して Contacts\Key Contacts フォルダーのフォルダー パスを取得します。 次に、FolderPath プロパティを引数として使用して、GetFolder メソッドを呼び出します。 GetFolder がフォルダーを返すと、Key Contacts が見つかったことを示すメッセージが表示されます。 GetFolder メソッドはフォルダーへのパスを取得して、適切な Folder オブジェクトを返します。 この処理は、まず FolderPath プロパティを string 配列に分割し、次にその配列を使用して FolderPath プロパティの先頭から始まる適切な Folder オブジェクトを検出することによって実行されます。 指定されたフォルダーが見つからない場合、GetFolder は NULL 参照を返します。
Visual Studio を使用してこのコード例をテストする場合、Microsoft.Office.Interop.Outlook 名前空間をインポートするときに、まず Microsoft Outlook 15.0 オブジェクト ライブラリ コンポーネントへの参照を追加し、Outlook 変数を指定します。 using ステートメントは、コード例の関数の前に直接置くことはできません。パブリッククラス宣言の前に追加する必要があります。 次のコード行は、C# でインポートおよび割り当てを行う方法を示しています。
using Outlook = Microsoft.Office.Interop.Outlook;
private void GetKeyContacts()
{
string folderPath =
Application.Session.
DefaultStore.GetRootFolder().FolderPath
+ @"\Contacts\Key Contacts";
Outlook.Folder folder = GetFolder(folderPath);
if (folder != null)
{
//Work with folder here
Debug.WriteLine("Found Key Contacts");
}
}
// Returns Folder object based on folder path
private Outlook.Folder GetFolder(string folderPath)
{
Outlook.Folder folder;
string backslash = @"\";
try
{
if (folderPath.StartsWith(@"\\"))
{
folderPath = folderPath.Remove(0, 2);
}
String[] folders =
folderPath.Split(backslash.ToCharArray());
folder =
Application.Session.Folders[folders[0]]
as Outlook.Folder;
if (folder != null)
{
for (int i = 1; i <= folders.GetUpperBound(0); i++)
{
Outlook.Folders subFolders = folder.Folders;
folder = subFolders[folders[i]]
as Outlook.Folder;
if (folder == null)
{
return null;
}
}
}
return folder;
}
catch { return null; }
}