Windowsのシステム管理をプログラムから行う際には、ADSI(Active Directory Services Interfaces)を利用することになります。.NET Frameworkでも当然サポートしています。~
 [[WSHの場合>WSH/ADSI]]と比較してみてください。

#contents
#br

** ユーザ管理
 C#でWindowsのユーザ、グループを登録、削除するには、System.DirectoryServices.dllアセンブリを参照します。コードは以下のようになります。NT系OS(WinNT,Win2000,WinXP,Win2003)で有効です。

*** 新規ユーザの登録
 // ユーザの作成
 DirectoryEntry AD = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer");
 DirectoryEntry NewUser = AD.Children.Add("TestUser", "user");
 NewUser.Invoke("SetPassword", new object[] {"TestPassword"});
 NewUser.Invoke("Put", new object[] {"Description", "C#コードで自動作成されたユーザ"});
 NewUser.Invoke("Put", new object[] {"FullName", "テスト ユーザ"});
 //ユーザの作成を確定する
 NewUser.CommitChanges();
 
 // Guestsグループにユーザを登録する。
 DirectoryEntry grp;
 grp = AD.Children.Find("Guests", "group");
 if (grp != null) {
   grp.Invoke("Add", new object[] {NewUser.Path.ToString()});
 }
 AD.Dispose();
 NewUser.Dispose();
 grp.Dispose();
 
 Console.WriteLine("アカウントは正常に作成されました");

 Add()で既に存在する名前のユーザを作成しようとしたり、Find()でグループが見つからなかったりすると、System.Runtime.InteropServices.COMException となるので、注意が必要です。

*** ユーザの削除
 DirectoryEntry AD = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer");
 DirectoryEntry User = AD.Children.Find(UID, "user");
 AD.Children.Remove(User);
 AD.Dispose();

*** ユーザがグループに所属しているかどうか判定する。
 DirectoryEntry AD = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer");
 DirectoryEntry grp = AD.Children.Find("Administrators","group");
 if (grp != null) {
   bool flag = (bool)grp.Invoke("IsMember", new object[] {User.Path.ToString()});
 }
 grp.Dispose();

** IIS管理
 ADSIでアクセス可能なディレクトリ構造と実際のフォルダは必ずしも一致しないので、事前の存在チェックやエラー処理が必要になるでしょう。

*** Webコンテンツの認証方法の設定
 例えばwwwroot直下のtestフォルダに対してNTLM認証のみに設定する場合は以下のようになります。
 string path = "IIS://" + System.Environment.MachineName + "/W3SVC/1/ROOT/test";
 DirectoryEntry entry = new DirectoryEntry(path);
 entry.Properties["AuthAnonymous"][0] = false;
 entry.Properties["AuthBasic"][0] = false;
 entry.Properties["AuthNTLM"][0] = true;
 entry.CommitChanges();

*** Webコンテンツのアクセス権限の設定
 例えばwwwroot直下のtestフォルダに対して読み取りのみに設定する場合は以下のようになります。ついでにディレクトリの参照も不許可に。
 string path = "IIS://" + System.Environment.MachineName + "/W3SVC/1/ROOT/test";
 DirectoryEntry entry = new DirectoryEntry(path);
 entry.Properties["AccessRead"][0] = true;
 entry.Properties["AccessWrite"][0] = false;
 entry.Properties["AccessExecute"][0] = false;
 entry.Properties["EnableDirBrowsing"][0] = false;
 entry.CommitChanges();


cf. [[Web site Administration with ADSI and the .NET DirectoryServices Namespace:http://www.15seconds.com/issue/010710.htm]]

cf. 
-[[Web site Administration with ADSI and the .NET DirectoryServices Namespace:http://www.15seconds.com/issue/010710.htm]]
-[[KeyType:http://www.microsoft.com/japan/technet/treeview/default.asp?url=/japan/technet/prodtechnol/windowsserver2003/proddocs/standard/ref_mb_keytype.asp]]

トップ   編集 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS