Launching exe using Process hangs on user input in c# - c#

I am launching an exe using below code.I am able to run exe successfully but it haults for user input which asks user to enter a character'y' or 'n'(i.e. yes/No).What I want is that while running exe (silent installation i.e. no cmd window is available or no user interaction) i should be able to pass 'y' character as user input.
Below is my code
public bool launchExe(exeFilepath)
{
bool status = true;
try
{
using (var myProcess = new Process())
{
myProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
myProcess.StartInfo.CreateNoWindow = true;
myProcess.StartInfo.UseShellExecute = true;
myProcess.EnableRaisingEvents = true;
myProcess.StartInfo.WorkingDirectory = exeFilepath;
myProcess.StartInfo.FileName = "Launcher.exe";
myProcess.Start();
myProcess.WaitForExit();
if (myProcess.ExitCode == 0)
status = true;
else
status = false;
}
}
catch (Exception ex)
{
Logger.Information(ex.Message);
status = false;
}
return status;
}

Use ProcessStartInfo.RedirectStandardInput to write to your launched Process:
myProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
myProcess.StartInfo.CreateNoWindow = true;
myProcess.EnableRaisingEvents = true;
myProcess.StartInfo.WorkingDirectory = exeFilepath;
myProcess.StartInfo.RedirectStandardInput = true;
myProcess.Start();
Thread.Sleep(1000); // wait 1 second
StreamWriter myStreamWriter = myProcess.StandardInput;
myStreamWriter.WriteLine("y");

Related

How to automatically close the process that is started by application, when application closes in c#?

I am getting wired problem with a process that is started by my c# application,in my application i start a process that runs a ffmpeg command which executes well but when in any how if i closes my application then that process still continues to executes.
private static bool RunRecordProcess(string command)
{
Process process = new Process();
try
{
ProcessStartInfo processStartInfo = new
ProcessStartInfo(Application.StartupPath +
FFMPEG_EXE_FILE_PATH);
processStartInfo.UseShellExecute = false;
processStartInfo.Arguments = "-hide_banner -loglevel 8 " +
command;
processStartInfo.RedirectStandardError = true;
processStartInfo.RedirectStandardOutput = true;
processStartInfo.RedirectStandardInput = true;
processStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
processStartInfo.CreateNoWindow = true;
processStartInfo.Verb = "";
process.EnableRaisingEvents = true;
process.StartInfo = processStartInfo;
process.Start();
string error = process.StandardError.ReadToEnd();
if (error.Length > 0)
{
if (!process.HasExited)
{
process.Kill();
//throw new Exception("Failure some error occured");
}
}
process.WaitForExit();
}
catch(Exception ex)
{
process.Kill();
ExceptionHandler.handleException(ex);
return false;
}
return true;
}
What i want is when my application exits my process that is started by the application will automatically exit so that no useless process will be using my system Cpu.
Thankyou!
You should create job object (CreateJobObject function in kernel32). There is more description:
https://tulisanlain.blogspot.com/2016/08/kill-child-process-when-parent-exit-c.html

"Multi-Step" commands while using CMD.exe in C#

I'm trying to use "multi-step" command in a c# script, for example the command "net user usrname *" contains 3 steps to enter a password and then validate, i don't know if it is possible to send extra arguments while the Process is running
My code:
Process p = new Process();
p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "/C " + command;
p.StartInfo.WorkingDirectory = startupFolder;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.UseShellExecute = false;
p.Start();
string output = p.StandardOutput.ReadToEnd();
string error = p.StandardError.ReadToEnd();
You would concatenate each command with "&". For example, "cmd /k echo Test 1 & echo test 2".
Edit:
I created a remote control/remote admin solution a while back that uses this same technique to allow you to run batch and PowerShell scripts against remote computers via the web portal. As shown in the below screenshot, it works.
The C# that executes the command can be found here: https://github.com/Jay-Rad/InstaTech_Client/blob/master/InstaTech_Service/Socket.cs#L614
if (cmdProcess == null || cmdProcess.HasExited)
{
var psi2 = new ProcessStartInfo("cmd.exe", "/k " + command);
psi2.RedirectStandardOutput = true;
psi2.RedirectStandardInput = true;
psi2.RedirectStandardError = true;
psi2.UseShellExecute = false;
psi2.WorkingDirectory = Path.GetPathRoot(Environment.SystemDirectory);
cmdProcess = new Process();
cmdProcess.StartInfo = psi2;
cmdProcess.EnableRaisingEvents = true;
cmdProcess.OutputDataReceived += async (object sender, DataReceivedEventArgs args) =>
{
jsonMessage.Status = "ok";
jsonMessage.Output = args.Data;
await SocketSend(jsonMessage);
};
cmdProcess.ErrorDataReceived += async (object sender, DataReceivedEventArgs args) =>
{
jsonMessage.Status = "ok";
jsonMessage.Output = args.Data;
await SocketSend(jsonMessage);
};
cmdProcess.Start();
cmdProcess.BeginOutputReadLine();
cmdProcess.BeginErrorReadLine();
}
else
{
cmdProcess.StandardInput.WriteLine(command);
}

Start hidden process with different credentials in c#

I am starting a process with different user credential. I want that this process start as hidden. I am using fallowing code.But it doesn't work. The process starts as visible.
private void f(){
try {
System.Security.SecureString ssPwd = new System.Security.SecureString();
Process process = new Process();
process.StartInfo.UseShellExecute = false;
process.StartInfo.FileName = "app.exe";
process.StartInfo.Arguments = "Params";
process.StartInfo.LoadUserProfile = true;
process.StartInfo.Domain = domain;
process.StartInfo.UserName = username;
for (int x = 0; x < password.Length; x++) {
ssPwd.AppendChar(password[x]);
}
process.StartInfo.Password = ssPwd;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
process.Start();
process.WaitForExit();
} catch (Exception ex) {
Console.WriteLine("Exception occurred. " + ex.Message);
}
}

Problems using cmd with unity

I'm trying to run command prompt from unity, my problem is that I can't find a way to fetch the result, here's my code
Process myProcess = new Process();
myProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
myProcess.StartInfo.CreateNoWindow = true;
myProcess.StartInfo.UseShellExecute = false;
myProcess.StartInfo.RedirectStandardOutput = true;
myProcess.StartInfo.FileName = "C:\\Windows\\system32\\cmd.exe";
string path = "C:\\Users\\Sam\\Desktop\\Test\\rubik3Sticker.generator";
myProcess.StartInfo.Arguments = "call " + path;
myProcess.EnableRaisingEvents = true;
myProcess.Start();
until here it gives no exceptions, but unity crashes when I try to add this:
while(!myProcess.StandardOutput.EndOfStream)
print(myProcess.StandardOutput.ReadLine());
any kind of help would be appreciated, thanks!

.NET Process fails on Windows 8

I have two weird problems running an app on Windows 8 (which works fine on Windows 7)
I'm running external "a.exe" app.
First issue is that when I run "a.exe" using Process - I don't get any output.
If I run a batch file which executes "a.exe" and write output to a file - there is an output.
The second issue is that in both cases (Batch and Process) "a.exe" fails. But from command line it works.
Here is the code:
proc = new Process();
proc.StartInfo.FileName = Path;
proc.StartInfo.Arguments = args;
proc.StartInfo.WorkingDirectory = GetDirectoryName(Path);
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.Verb = "runas administrator";
proc.OutputDataReceived += (sendingProcess, line) =>
{
string s = line.Data;
if (!string.IsNullOrWhiteSpace(s))
{
_sbStdout.AppendLine(line.Data);
}
};
proc.ErrorDataReceived += (sendingProcess, line) =>
{
string s = line.Data;
if (!string.IsNullOrWhiteSpace(s))
{
_sbStderr.AppendLine(line.Data);
}
};
proc.Start();
proc.BeginOutputReadLine();
proc.BeginErrorReadLine();
// Wait for exit or timeout
bool res = true;
if (timeout <= 0 || timeout == null)
proc.WaitForExit();
else
res = proc.WaitForExit((int)timeout);
ExitCode = proc.ExitCode;
What is wrong?

Categories