Question

I am trying to create an app that can kill a user's session on a terminal server. I have written the following code:

string host = "terminalServer";
string user = "domain\criso";
string sid = "4";

System.Diagnostics.Process proc = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();

startInfo.CreateNoWindow        = true;
startInfo.FileName              = @"logoff.exe";
startInfo.Arguments             = @"/SERVER:" + host + " " + sid;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute       = false;
proc.StartInfo                  = startInfo;
proc.Start();
proc.WaitForExit();

// Catch error
if (proc.ExitCode != 0)
{
    StreamReader reader = proc.StandardError;
    string errorMessage = reader.ReadToEnd();

    MessageBox.Show(@"ERROR " + proc.ExitCode.ToString() + ": " + errorMessage);
}
else
    StatusLabel.Text = user + @"'s Session terminated";

The code above returned error "Couldn't find the file specified" message when executed. I have tried the combination of path to go to C:\windows\system32\logoff.exe but still get the same error message.

I have also tried to invoke cmd.exe process with following argument:

@"/C logoff /SERVER:" + host + " " + sid

it returned with "'logoff' is unrecognized as internal or external command, opreable program or batch file." and still no luck.

Anyone has ever solved this problem before? For extra information, I am using windows 7 and the terminal server is windows server 2003 & 2008 r2 (there are multiple servers). And if I run 'logoff' command directly from command prompt, it works fine killing my session.

Was it helpful?

Solution

I found the solution by including 'logoff.exe' into the project and set 'Copy to output directory' property of 'logoff.exe' to yes or copy if newer, which then I don't need to specify the full path on my Process.Start calling.

What's odd is that when I tried to include 'logoff.exe' into my project, VS file explorer didn't list the 'logoff.exe' under 'C:\windows\system32\' directory, but the executable is there if i get into the directory by windows' regular file explorer.

UPDATE

As pointed out in the comment, it looks like that when the app is trying to look into the system32 folder, it is interrupted by syswow64 layer somehow. Based on the comment I found a switch in the project settings to build the app as 32-bit, I turned it off and the app can now call 'logoff.exe' without any issue. But when I try to add existing file from VS file explorer, it still wouldn't list the complete content of the system32 folder (as it was looking into syswow64 folder instead).

enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top