I'm trying to reset Windows local administrator password with .Net process as follows:
int retVal;
string pEXE = Environment.GetFolderPath(Environment.SpecialFolder.System) + @"\cmd.exe";
if (System.IO.File.Exists(pEXE))
{
Process P = new Process();
P.StartInfo.FileName = pEXE;
P.StartInfo.Arguments = "/c " + "net user lAdmin 123";
P.StartInfo.UseShellExecute = false;
P.StartInfo.CreateNoWindow = true;
P.StartInfo.RedirectStandardError = true;
P.StartInfo.RedirectStandardOutput = true;
P.StartInfo.RedirectStandardInput = true;
P.Start();
P.WaitForExit();
retVal = P.ExitCode;
}
Under two different cases: [1] If local administrator account username is 'lAdmin' the exit code would be '0' which means of success. [2] If local administrator account username is 'Administrator' the exit code would be '2' which is 'The system cannot find the file specified', however if I ran this command in Windows command prompt I get error code '2221' which is 'The user name could not be found'.
net.exe just shows the error code "2221" to the user so that the user can lookup this code in the documentation, but it does not make the code "2221" available to the operating system.
The error code returned is also 2 when executing this in the command prompt as can be seen by using echo %errorlevel%
afterwards.
You could try to capture the output of the command and then parse the output to retrieve the error code shown to the user. But parsing that text will not be very reliable because the text obviously differs in different languages of the operating system and may also change in future Windows updates.
Some sample code how you would do that (not tested with non-European versions of Windows)
int retVal;
string pEXE = Environment.GetFolderPath(Environment.SpecialFolder.System) + @"\cmd.exe";
if (System.IO.File.Exists(pEXE))
{
Process P = new Process();
P.StartInfo.FileName = pEXE;
P.StartInfo.Arguments = "/c " + "net user lAdmin 123";
P.StartInfo.UseShellExecute = false;
P.StartInfo.CreateNoWindow = true;
P.StartInfo.RedirectStandardError = true;
P.StartInfo.RedirectStandardOutput = true;
P.StartInfo.RedirectStandardInput = true;
P.Start();
P.WaitForExit();
retVal = P.ExitCode;
if(retVal != 0)
{
// Error code was returned, get text output
string outputText = P.StandardError.ReadToEnd();
// Parse error code from text output
Match match = Regex.Match(outputText, "NET HELPMSG (?<code>\\d+)");
if(match != null)
{
string code = match.Groups["code"].Value;
retVal = int.Parse(code);
}
}
MessageBox.Show(retVal.ToString());
}