LoginSignup
2
3

More than 5 years have passed since last update.

ActiveDirectory環境下で、ログインユーザのメールアドレスを取得する(恐らく)一番簡単で堅い方法

Last updated at Posted at 2017-04-27

準備

VisualStudioでプロジェクトを作って下さい。
で、参照設定で以下の二つを追加します。

image

image

実装

例外処理はいい加減。

using System;
using System.DirectoryServicies;
using ActiveDS;

class Program {
    static void Main () {
        Console.WriteLine(MyMailAddress);
    }

    static string MyMailAddress {
        get {
            try {
                using (DirectoryEntry DE = new DirectoryEntry(string.Format("LDAP://{0}", new ADSystemInfo().UserName))) {
                    return DE.Properties["mail"].Value as string;
                }
            }
            catch {
                return null;
            }
        }
    }
}

解説

  • ADSystemInfoをインスタンス化すると、ログインユーザの情報が取得できる
  • その中のUserNameプロパティは、ActiveDirectory環境に於いてはそのユーザのdn(=distinguishedName)が入っている
  • dnはActiveDirectory内での一意な識別名である
  • DirectoryServiceのコンストラクタに『LDAP://dn名』 を渡すと一発でディレクトリエントリが取れる
    ※条件を考えたり複数オブジェクトがヒットしたらどうしよう、とか余計な事を考えずに済む
  • で、そこからmailプロパティにアクセスすればおっけー、と云う訳
  • 勿論、他のプロパティにアクセスしても良いですよ

以上

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3