error invoking logoff.exe - c#

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.

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).

Related

How do i include batch files inside of my .exe Instead of needing them in the folder the .exe is located in

So been searching or the web but can't seem to find an answer that has helped me. I have been looking for almost a week now.
I created a program in vs, alongside with some batch files. The Batch files run great by themselves and through the debug/release when including them in the folder with the .exe.
My problem is I want to be able to ONLY have the .exe file from my release and it still work.
Is there a way i can build these files inside the .exe? I have tried using c# to write my console commands instead of including seperate batch files. But im pretty new to c# and i get nothing but errors with the commands i want to run/if i run to many lines.
I would much rather have just c# instead of including the batch files but that I can't seem to figure out a solution to either.
Any help would be appreciated.
This is me currently calling batch files which works just fine. Again, if there is a way to just write this in c# instead of calling a batch file I would be happy to learn.
Process process = new Process();
ProcessStartInfo psi = new ProcessStartInfo();
psi.CreateNoWindow = false;
psi.Verb = "runas";
psi.FileName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + #"/" + "undo.bat";
psi.UseShellExecute = true;
process.StartInfo = psi;
_ = process.Start();
process.WaitForExit();
I'm starting CyberSecurity soon and am playing around with some Security stuff on my computer. Below is a sample code from my batch file to enable Security Protocols. If anything how would i write this in c#?
echo ...
echo Enabling Windows Firewall
netsh advfirewall set allprofiles state on
echo Enalbing HyperVisor
bcdedit /set hypervisorlaunchtype auto
echo Enabling UAC
%windir%\System32\reg.exe ADD HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v EnableLUA /t REG_DWORD /d 1 /f
echo.
echo.
echo Your Computer will now be restarting for changes to take effect!
timeout 10
shutdown /r /t 001
What you can do is include the batchfiles as embedded resources in your project. Then read them and then execute them.
to include them as embedded resources example...
add them to your project.
right click and go to properties
select embedded resource
then to extract...
Write file from assembly resource stream to disk
you can then write the file to disk and create process on it. or there is a way to execute cmd.exe without writing the file to disk but this is a little complicated so the best way is to just write to disk.
Execute BATCH script in a programs memory
I followed the guide given above and a few others to get my solution to work. Embed the resource that's in your solution, then I used the following code to pretty much create the functions of being able to write it.
private static void Extract(string nameSpace, string outDirectory, string internalFilePath, string resourceName)
{
Assembly assembly = Assembly.GetCallingAssembly();
using (Stream s = assembly.GetManifestResourceStream(nameSpace + "." + (internalFilePath == "" ? "" : internalFilePath + ".") + resourceName))
using (BinaryReader r = new BinaryReader(s))
using (FileStream fs = new FileStream(outDirectory + "//" + resourceName, FileMode.OpenOrCreate))
using (BinaryWriter w = new BinaryWriter(fs))
w.Write(r.ReadBytes((int)s.Length));
}
Here is what I used to save, execute then delete the file.
Extract("nameSpace", "outDirectory", "internalFilePath", "resourceName");
Process process = new Process();
ProcessStartInfo psi = new ProcessStartInfo();
psi.CreateNoWindow = false;
psi.Verb = "runas";
psi.FileName = #"C:/" + "resourceName";
psi.UseShellExecute = true;
process.StartInfo = psi;
_ = process.Start();
process.WaitForExit();
System.Threading.Thread.Sleep(10);
if ((System.IO.File.Exists(psi.FileName)))
{
System.IO.File.Delete(psi.FileName);
}
Keep in mind im new when it comes to this so im sure there is a better way of writing it, but this worked for me!

Call to Process works fine with Debug, but it doesn't work in the installed application

I am developing a Windows Form program that has callings to ffmpeg library through the class Process.
It works fine when I run it with the Debug in Visual Studio 2013. But when I install the program and I invoke the operation that call to the ffmpeg Process, it doesn't work. The cmd screen appears an disappears and nothing happens.
I have tried to know what can be happening getting a log file with the output of ffmpeg, in case it was a problem in the ffmpeg libraries. However, after executing it the log is empty, what means that the ffmpeg command has not been executed.
Can someone help me, please?
The code is this:
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "/c " + ffmpegPath + " " + commandArguments;
using (Process processTemp = new Process())
{
processTemp.StartInfo = startInfo;
processTemp.EnableRaisingEvents = true;
processTemp.Start();
processTemp.WaitForExit();
}
I am invoking to cmd.exe (not directly ffmpeg.exe) because in the arguments sometimes there can be a pipe (that is why the command starts with "/c").
Are you sure this isn't a privileges issue when trying to execute the cmd.exe (e.g you need administrator privileges)
try adding
startInfo.Verb = "runas";
Paul
Hmm its not a path issue with spaces in file/directory names is it? For ffmpegPath or one of your command parameters (if a file path). Surround all file paths with ' like below.
Try surrounding any file paths with '
startInfo.Arguments = "/c '" + ffmpegPath + "' " + commandArguments;
Also you could try adding /K to the cmd command call to stop if from closing the command prompt when it finishes. It might tell you the error before it closes the window but you wont see it if it closes so quickly
Good luck :)
Paul

Launch an app running as admin - by passing the filename.sln (UseShellExecute)

I can call Process.Start(filename.sln) and it launches VisualStudio with that solution.
But doing so using ProcessStartInfo with Verb="runas" and I get an exception. Even with UseShellExecute=true.
Is there a way to launch an app running as admin where I pass it the app's data file and don't have the application.exe filename?
Found the answer - when you run as admin you can only give it the executable file, not the app for the program to run. So you have to pass devenv.exe, not filename.sln
ProcessStartInfo processInfo = new ProcessStartInfo(); //new process class
processInfo.Verb = "runas"; //wanna admin rights
processInfo.FileName = sDevPath + "devenv.exe"; //exe file path
processInfo.Arguments = sPrjPath + "mConverter.sln"; //sln file as argument
try
{
Process.Start(processInfo); //try to start
}
catch (Win32Exception)
{
//oops
}

iisreset on remote machine (C#)

Process myProcess = new Process();
ProcessStartInfo remoteAdmin =
new ProcessStartInfo(Environment.GetFolderPath(Environment.SpecialFolder.System) + #"\iisreset.exe /restart");
remoteAdmin.UserName = username;
remoteAdmin.Password = pwd;
remoteAdmin.Domain = domain;
myProcess.StartInfo = remoteAdmin;
myProcess.StartInfo.UseShellExecute = false;
myProcess.StartInfo.RedirectStandardOutput = true;
myProcess.Start(); --- ERROR HERE
Can not find the file specified.
But when I try to run iisreset on the local machine by cmd it's working.
Unless I'm missing something, (Environment.GetFolderPath(Environment.SpecialFolder.System) will get back the local machine (Where the code is running) special folder. So it's expecting the file C:\Windows\System\iisreset.exe to be located on your machine. The only method I could see to get around this, is to drop the C:\ and instead add in the device's name \\DeviceName\C$\ and then the filepath. This is assuming the special folder system is located in the same place on your machine and the remote machine.
The only other method, to get the remote machines system directory is to get it via WMI or via a reg entry reading.
So if using WMI:
"SELECT * FROM Win32_OperatingSystem"
Once done, you would then need to build the folder string yourself from that.
There is no file called C:\Windows\System\iisreset.exe /restart (assuming that Environment.GetFolderPath(Environment.SpecialFolder.System) returns C:\Windows\System\
So you would want
ProcessStartInfo remoteAdmin =
new ProcessStartInfo(Environment.GetFolderPath(Environment.SpecialFolder.System) + "iisreset.exe");
remoteAdmin.Arguments = "/restart";
But Environment.GetFolderPath(Environment.SpecialFolder.System) probably returns something like C:\Windows\System (note no trailing slash), and there is definitely no file called c:\windows\systemiisreset.exe
So you would actually want
ProcessStartInfo remoteAdmin =
new ProcessStartInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "iisreset.exe"));
remoteAdmin.Arguments = "/restart";
iisreset.exe supports remote calls, so instead of using WMI to get remote directory you can actually just do:
iisreset {servername}

Process.Start() edmgen

after clicking on button in asp.net application process.start() runs edmgen tool with arguments. And I catch error :
var cs =ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
string myArgs="/mode:fullgeneration /c:\""+cs+"\" /project:nwd /entitycontainer:SchoolEntities /namespace:SchoolModel /language:CSharp ";
string filename= GetFrameworkDirectory() + "\\EdmGen.exe";
ProcessStartInfo startInfo = new ProcessStartInfo(filename,myArgs);
startInfo.UseShellExecute = false;
//startInfo.RedirectStandardError = true;
Process myGenProcess = Process.Start(startInfo);
//genInfo.Text = myGenProcess.StandardError.ReadToEnd();
How to fix this?
You need to pass the full path to a folder that you have write access to for the output.
Well the error indicates that you don't have access to "C:\Program Files\Common Files\Microsoft Shared\DevServer\10.0\nwd.ssdl".
Check that your process has the necessary permissions on the file and all the folders up the tree.

Categories

Resources