C# – How to use net user with c#

ccommandnetshell

I am trying to use net user with c#

System.Diagnostics.ProcessStartInfo proccessStartInfo = new System.Diagnostics.ProcessStartInfo("net user " + id + " /domain");

proccessStartInfo.CreateNoWindow = true;
System.Diagnostics.Process proc = new System.Diagnostics.Process {StartInfo = proccessStartInfo};
proc.Start();

string result = proc.StandardOutput.ReadToEnd();
textBoxOp.Text = result;

When the I execute the code Win32 exception occurs with message The system cannot find the file specified

Details of exceptions are as follows

at
System.Diagnostics.Process.StartWithShellExecuteEx(ProcessStartInfo
startInfo) at GetUserFromAD.Form1.GetInformation(String id) in
D:\GetUserFromAD\GetUserFromAD\Form1.cs:line 25 at
GetUserFromAD.Form1.button_Click(Object sender, EventArgs e) in
D:\Ram\MyC#\GetUserFromAD\GetUserFromAD\Form1.cs:line 35 at
System.Windows.Forms.Control.OnClick(EventArgs e) at
System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent) at
System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons
button, Int32 clicks) at
System.Windows.Forms.Control.WndProc(Message& m) at
System.Windows.Forms.ButtonBase.WndProc(Message& m) at
System.Windows.Forms.Button.WndProc(Message& m) at
System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd,
Int32 msg, IntPtr wparam, IntPtr lparam) at
System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at
System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32
dwComponentID, Int32 reason, Int32 pvLoopData) at
System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32
reason, ApplicationContext context) at
System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32
reason, ApplicationContext context) at GetUserFromAD.Program.Main()
in D:\Ram\MyC#\GetUserFromAD\GetUserFromAD\Program.cs:line 18 at
System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state) at
System.Threading.ThreadHelper.ThreadStart()

Best Answer

net is the command. Everything from user onwards are command arguments. As such, you'll need to use the following constructor:

System.Diagnostics.ProcessStartInfo proccessStartInfo = new System.Diagnostics.ProcessStartInfo("net", "user " + id + " /domain");

In addition, in order to capture the standard output you'll need to set the following properties before you call proc.Start()

proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.UseShellExecute = false;
Related Topic