C#でクラス間での変数の使用

C#でtextboxにuser名とpasswordを入力させ、windowsユーザーを作成するプログラムを書いています。

C#

namespace WpfApp1 { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } public void TextBox_password(object sender, TextChangedEventArgs e) { } public void TextBox_username(object sender, TextChangedEventArgs e) { } public void Button_Click(object sender, RoutedEventArgs e) { string username; username = usernamebox.Text; string password; password = usernamebox.Text; DirectoryEntry de = new($"WinNT://{Environment.MachineName},computer"); DirectoryEntry newUser = de.Children.Add(username, "user"); newUser.Invoke("SetPassword", new object[] { password }); newUser.CommitChanges(); DirectoryEntry grp = de.Children.Find("Guests", "group"); if (grp != null) { grp.Invoke("Add", new object[] { newUser.Path.ToString() }); } } }}

上のコードを実行すると、次の例外が発生してしまいます。

System.Runtime.InteropServices.COMException: '指定されたユーザー名は無効です。

原因は変数の値にtextboxの内容が入っていないことでしょう。
それを元にかなり検索しましたが、どれもピンと来ませんでした...
クラス間で変数を利用すると思うのですが、その場合のコードはどのようになるのでしょうか?
かなり基礎的なものだと思いますが、理解ができなかったので教えていただけると幸いです。

コメントを投稿

0 コメント