Run .exe from another app and enter values automatically - c#

I want to run .exe file from another app, which is console app in .NET Core. When the app is open I want to write input to console from my code. Something like this:
var cmd = System.Diagnostics.Process.Start("myApp.exe");
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.UseShellExecute = false;
cmd.Start();
cmd.StandardInput.WriteLine("MyName"); // this should be entered in console as username
So I specify username from my code, instead of writing it to console manually. Code above is not working for me. Is there a way to do this?
enter username

You're first starting the Process and then you're manipulating the startup arguments. You need to start the process afterwards.
use something like this instead:
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.UseShellExecute = false; //required to redirect standart input/output
// redirects on your choice
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.FileName = ...app path to execute...;
startInfo.Arguments = ...argumetns if required...;
Process process = new Process();
process.StartInfo = startInfo;
process.Start();
process.StandardInput.WriteLine(...write whatever you want...);
source

You need redirect standard input. Create ProcessStartInfo structure, then start a process and after process started write to the process standart input
ProcessStartInfo processStartInfo = new ProcessStartInfo
{
FileName = pathToApplication,
RedirectStandardInput = true,
UseShellExecute = false
};
Process process = Process.Start(processStartInfo);
var writer = process.StandardInput;
writer.WriteLine("MyName");
Console.ReadLine();

Related

C# Piping Linux Command Output in Process

I am having trouble with the Process class to pipe a command on a Linux system.
I want to execute the following command: rpm2cpio repo.rpm | cpio -divm
I've tried
process.StartInfo.FileName = "rpm2cpio;
rocess.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.Arguments = "repo.rpm | cpio - idmv";
But the program hangs.
Similarly, I tried saving the output from rpm2cpio to a string or an output file and then pass that as the argument for the cpio command, but it also hangs.
process.StartInfo.FileName = "cpio";
rocess.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.Arguments = "-idvm < output.txt";
// or
process.StartInfo.Arguments = "-idvm < " + rp2cpio_output;
What are some ways I can get this working? I saw this post with a solution, but it is on a Window's system. How do the same thing on Linux?
Setting process.StartInfo.RedirectStandardOutput=true will cause the program to redirect standard output to the stream process.StartInfo.StandardOutput. When this happens the program will hang until you read from standard output.
To get the behavior I think you are looking for, you just need to set RedirectStandardOutput=false. That way the pipes and redirects in your command will work as expected.
Rather than directly writing to a file, you can simply use a StreamWriter to fetch the output in a stream buffer and then use that to write to the file. If the process still hangs, simply use the timeout command of linux to terminate the process.
The following snippet may help after making a few changes:
ProcessStartInfo processStartInfo = new ProcessStartInfo();
processStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
processStartInfo.FileName = "/bin/bash";
processStartInfo.WorkingDirectory = "/";
string cmd = "timeout 1 cat > temp.txt";
var escapedArgs = cmd.Replace("\"", "\\\"");
processStartInfo.Arguments = $"-c \"{escapedArgs}\"";
processStartInfo.UseShellExecute = false;
processStartInfo.RedirectStandardInput = true;
processStartInfo.RedirectStandardOutput = true;
processStartInfo.RedirectStandardError = true;
processStartInfo.StandardErrorEncoding = System.Text.Encoding.UTF8;
processStartInfo.StandardInputEncoding = System.Text.Encoding.UTF8;
processStartInfo.StandardOutputEncoding = System.Text.Encoding.UTF8;
processStartInfo.UseShellExecute = false;
process.StartInfo = processStartInfo;
process.Start();
stdIOWriter = process.StandardInput;
stdIOWriter.WriteLine("Hey Fellas");
String error = process.StandardError.ReadToEnd();
String output = process.StandardOutput.ReadToEnd(); ```

How to run Defrag.exe for optimize the harddisk in windows application c#

I have developed one windows application in which i have some implemented feature now i want to implement optimize hard disk so i got to know about defrag.exe .so i wrote some code but its not working for me. can anyone what am doing wrong ?
Process p = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo();
p.StartInfo.Verb = "runas";
p.StartInfo.FileName =
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "Defrag.exe");
p.StartInfo.Arguments = #"c:\ /A";
try
{
p.Start();
p.WaitForExit();
string a= p.StandardOutput.ToString();
See my comment on your previous post. That aside, you need to set a few extra parameters - working sample below. You may also need to elevate privileges in order for your scenario to work. If this is the case, then see this post.
static void Main(string[] args)
{
Process p = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo();
p.StartInfo.Verb = "runas";
p.StartInfo.FileName =
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "Defrag.exe");
p.StartInfo.Arguments = #"c:\ /A";
// Additional properties set
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = false;
p.Start();
// Fixed your request for standard with ReadToEnd
string result = p.StandardOutput.ReadToEnd();
p.WaitForExit();
}
Adding another option - try the below. To use runas, you need to set StartInfo.UseShellExecute = true which means you cant redirect the standard output - would this still work for you? Another option is to run your whole program as admin How do I force my .NET application to run as administrator? - this will allow you to redirect your output and run with elevated permissions.
static void Main(string[] args)
{
Process p = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo();
p.StartInfo.Verb = "runas";
p.StartInfo.FileName =
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "Defrag.exe");
p.StartInfo.Arguments = #"c:\ /A";
// Additional properties set
//p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = true;
//p.StartInfo.CreateNoWindow = true;
p.Start();
// Fixed your request for standard with ReadToEnd
//string result = p.StandardOutput.ReadToEnd();
p.WaitForExit();
}

Hide console window from Process.Start C#

I am trying to create process on a remote machine using using System.Diagnostics.Process class.
I am able to create a process. But the problem is, creating a service is take a long time and console window is displayed.
Another annoying thing is the console window is displayed on top of my windows form and i cant do any other operations on that form.
I have set all properties like CreateNoWindow = true,
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden
but still it shows the console window. even i have redirected output and errors to seperate stream but no luck.
Is there any other way to hide the Console window? Please help me out .
Here is the part of my code i used to execute sc command.
Process proc = new Process();
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
proc.StartInfo.FileName = "sc";
proc.StartInfo.Arguments = string.Format(#"\\SYS25 create MySvc binPath= C:\mysvc.exe");
proc.StartInfo.RedirectStandardError = false;
proc.StartInfo.RedirectStandardOutput = false;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = true;
proc.Start();
proc.WaitForExit();
I had a similar issue when attempting to start a process without showing the console window. I tested with several different combinations of property values until I found one that exhibited the behavior I wanted.
Here is a page detailing why the UseShellExecute property must be set to false.
http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.createnowindow.aspx
Under Remarks section on page:
If the UseShellExecute property is true or the UserName and
Password properties are not null, the CreateNoWindow property
value is ignored and a new window is created.
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = fullPath;
startInfo.Arguments = args;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
Process processTemp = new Process();
processTemp.StartInfo = startInfo;
processTemp.EnableRaisingEvents = true;
try
{
processTemp.Start();
}
catch (Exception e)
{
throw;
}
I've had bad luck with this answer, with the process (Wix light.exe) essentially going out to lunch and not coming home in time for dinner. However, the following worked well for me:
Process p = new Process();
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
// etc, then start process
This should work, try;
Add a System Reference.
using System.Diagnostics;
Then use this code to run your command in a hiden CMD Window.
Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
cmd.StartInfo.Arguments = "Enter your command here";
cmd.Start();
This doesn't show the window:
Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
cmd.StartInfo.CreateNoWindow = true;
...
cmd.Start();

How to hide cmd window while running a batch file?

How to hide cmd window while running a batch file?
I use the following code to run batch file
process = new Process();
process.StartInfo.FileName = batchFilePath;
process.Start();
If proc.StartInfo.UseShellExecute is false, then you are launching the process and can use:
proc.StartInfo.CreateNoWindow = true;
If proc.StartInfo.UseShellExecute is true, then the OS is launching the process and you have to provide a "hint" to the process via:
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
However the called application may ignore this latter request.
If using UseShellExecute = false, you might want to consider redirecting standard output/error, to capture any logging produced:
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.OutputDataReceived += new DataReceivedEventHandler(ProcessOutputHandler);
proc.StartInfo.RedirectStandardError = true;
proc.ErrorDataReceived += new DataReceivedEventHandler(ProcessOutputHandler);
And have a function like
private void ProcessOutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
{
if (!String.IsNullOrEmpty(outLine.Data)) // use the output outLine.Data somehow;
}
There's a good page covering CreateNoWindow this on an MSDN blog.
There is also a bug in Windows which may throw a dialog and defeat CreateNoWindow if you are passing a username/password. For details
http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=98476
http://support.microsoft.com/?kbid=818858
According to the Process properties, you do have a:
Property: CreateNoWindow
Notes: Allows you to run a command line program silently.
It does not flash a console window.
and:
Property: WindowStyle
Notes: Use this to set windows as hidden.
The author has used ProcessWindowStyle.Hidden often.
As an example!
static void LaunchCommandLineApp()
{
// For the example
const string ex1 = "C:\\";
const string ex2 = "C:\\Dir";
// Use ProcessStartInfo class
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = false;
startInfo.UseShellExecute = false;
startInfo.FileName = "dcm2jpg.exe";
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.Arguments = "-f j -o \"" + ex1 + "\" -z 1.0 -s y " + ex2;
try
{
// Start the process with the info we specified.
// Call WaitForExit and then the using statement will close.
using (Process exeProcess = Process.Start(startInfo))
{
exeProcess.WaitForExit();
}
}
catch
{
// Log error.
}
}
Use:
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
This is what worked for me,
When you redirect all of the input and output, and set the window hidden it should work
Process p = new Process();
p.StartInfo.RedirectStandardError = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
try with this and this where the c# code is embedded into the batch files:
#echo off
echo self minimizing
call getCmdPid.bat
call windowMode.bat -pid %errorlevel% -mode minimized
echo --other commands--
pause
Though it might be not so easy to unhide the window.

How do I hide a console application user interface when using Process.Start?

I want to run a console application that will output a file.
I user the following code:
Process barProcess = Process.Start("bar.exe", #"C:\foo.txt");
When this runs the console window appears. I want to hide the console window so it is not seen by the user.
Is this possible? Is using Process.Start the best way to start another console application?
Process p = new Process();
StreamReader sr;
StreamReader se;
StreamWriter sw;
ProcessStartInfo psi = new ProcessStartInfo(#"bar.exe");
psi.UseShellExecute = false;
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
psi.RedirectStandardInput = true;
psi.CreateNoWindow = true;
p.StartInfo = psi;
p.Start();
This will start a child process without displaying the console window, and will allow the capturing of the StandardOutput, etc.
Check into ProcessStartInfo and set the WindowStyle = ProcessWindowStyle.Hidden and the CreateNoWindow = true.
If you would like to retrieve the output of the process while it is executing, you can do the following (example uses the 'ping' command):
var info = new ProcessStartInfo("ping", "stackoverflow.com") {
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
};
var cmd = new Process() { StartInfo = info };
cmd.Start();
var so = cmd.StandardOutput;
while(!so.EndOfStream) {
var c = ((char)so.Read()); // or so.ReadLine(), etc
Console.Write(c); // or whatever you want
}
...
cmd.Dispose(); // Don't forget, or else wrap in a using statement
We have done this in the past by executing our processes using the Command Line programatically.

Categories