LoginSignup
5
8

More than 5 years have passed since last update.

C#覚書 net use コマンド

Posted at

VisualStusio2012のC#で、net useコマンドを使用してサーバーに接続しています。
実は、Javascript側で実施していた処理だったのですが、Edge対応でサーバーサイドで処理することになり調査・実装しました。

参考サイト

http://piyopiyocs.blog115.fc2.com/blog-entry-261.html
https://social.msdn.microsoft.com/Forums/ja-JP/7aa9ee0f-4ad2-436b-b5ed-ad11cc6f78e3/net-use?forum=csharpgeneralja
http://d.hatena.ne.jp/nurs/20130404/1365090460

ハマったところ

1. WaitforExitで待っても戻ってことない
  「/c」オプションを追加する事で解決。
  上記オプションを追加する事で、起動したコマンドプロンプト上で【コマンド】を実行した後、
  コマンドプロンプトを終了することになるそうです。
  (知らなかった…)

2. 接続出来ない
  ユーザーIDの前にドメイン名をつける事で解決。

実装ソース

接続処理

open.cs
// nert use 接続
                        System.Diagnostics.Process open = new System.Diagnostics.Process();
                        open.StartInfo.FileName = "cmd.exe";            // コマンド名
                        open.StartInfo.Arguments = "/c";                // 引数①
                        open.StartInfo.Arguments += "net user 接続先 パスワード /user:ユーザーID";            // 引数②
                        open.StartInfo.CreateNoWindow = true;           // DOSプロンプトの黒い画面を非表示
                        open.StartInfo.UseShellExecute = false;         // プロセスを新しいウィンドウで起動するか否か
                        open.StartInfo.RedirectStandardOutput = true;   // 標準出力をリダイレクトで取得したい
                        open.Start();
                        open.WaitForExit();

切断処理

close.cs
// nert use 接続
                        System.Diagnostics.Process open = new System.Diagnostics.Process();
                        open.StartInfo.FileName = "cmd.exe";            // コマンド名
                        open.StartInfo.Arguments = "/c";                // 引数①
                        open.StartInfo.Arguments += "net user 接続先 /delete";            // 引数②
                        open.StartInfo.CreateNoWindow = true;           // DOSプロンプトの黒い画面を非表示
                        open.StartInfo.UseShellExecute = false;         // プロセスを新しいウィンドウで起動するか否か
                        open.StartInfo.RedirectStandardOutput = true;   // 標準出力をリダイレクトで取得したい
                        open.Start();
                        open.WaitForExit();
5
8
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
5
8