I am having need to automate an external windows console application from C#. Application is basically interface to an external device. When I invoke application it will ask me for authentication ie to enter a password with prompt something like 'Enter password:'. Right now there is no way to configure this application to run without interactive password prompt.
So I want to automate same from C# by sending password whenever it prompts and then to fire come commands which will execute on external device and then grab output. I know about process class and I am having some pointers like I can use pipes for this purpose ( Not Sure ? ).
As I have not handled this kind of automation before I am looking for help / direction form this.
Thanks in Advance.
The way to do this is to use the Redirection members, e.g ProcessStartInfo.RedirectStandardInput Property
Process myProcess = new Process();
myProcess.StartInfo.FileName = "someconsoleapp.exe";
myProcess.StartInfo.UseShellExecute = false;
myProcess.StartInfo.RedirectStandardInput = true;
myProcess.StartInfo.RedirectStandardOutput = true;
myProcess.StartInfo.ErrorDialog = false;
myProcess.Start();
StreamWriter stdInputWriter = myProcess.StandardInput;
StreamReader stdOutputReader = myProcess.StandardOutput;
stdInputWriter.WriteLine(password);
var op = stdOutputReader.ReadLine();
// close this - sending EOF to the console application - hopefully well written
// to handle this properly.
stdInputWriter.Close();
// Wait for the process to finish.
myProcess.WaitForExit();
myProcess.Close();
Related
Is it possible to make a HIDDEN and unseen Call to a web browser for a simple single, invisible .PHP script/page with C# ?
Guys, i've got 1 simple thing that i'm doing from my MAIN C# APP, which is a program that does Text-Message Alerts. What i'd "LIKE" to do:
-After every Text-Message Send, call a simple and easy .PHP script (with the RESULTS of the Text-Message send: STATUS=GOOD||BAD||UNKNOWN,number,carrier
This quick+easy .PHP script and call is just to keep a database of KNOWN and WORKING (AND NON-WORKING) Numbers... a simple and modest task- I just don't want the ugly Web Browser (and it's multiple TABS) being shown AT ALL (I want it to be INVISIBLE, or ELSE I can't USE this .PHP Method of tracking the GOOD+BAD Text Numbers. It's NOT Gonna WORK if i can't just HIDE the browser window somehow or alternately call the .PHP script (WHICH HAS NO OUTPUT: all it does is write what the status, number, and carrier are to a FLAT FILE and it exits: QUICK+EASY like I said...).
But guys, tell me if this is just not possible the way I want it with my C#/.NET app here...?
Thanks in advance!
I don't know why you are doing this with PHP instead of doing everything you need in your C# app, but you can do this by running a hidden command line call process like this:
var startInfo = new System.Diagnostics.ProcessStartInfo
{
WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
FileName = "cmd.exe",
Arguments = "/C php <yourscript>"
};
var process = new System.Diagnostics.Process
{
StartInfo = startInfo
};
process.Start();
and then reading the output:
var output = process.StandardOutput.ReadToEnd();
I'm currently creating an application in C# that allows you to create a server and manage it easily, to do this it uses batch files to run said servers. It works by creating batch files and using those to run the server. (Java by the way).
So, what I'm wondering is if it's possible to grab the output from the console and rather than dumping it in a textbox and closing the console like the code below does, I need it to continually post any output from the console without closing and without spamming loads of consoles open (tried using a timer).
Process myProcess = new Process();
ProcessStartInfo myProcessStartInfo =
new ProcessStartInfo(batchfilelocation);
myProcessStartInfo.UseShellExecute = false;
myProcessStartInfo.RedirectStandardOutput = true;
myProcess.StartInfo = myProcessStartInfo;
myProcess.Start();
StreamReader myStreamReader = myProcess.StandardOutput;
// Read the standard output of the spawned process.
string myString = myStreamReader.ReadToEnd();
textBox1.Text = textBox1.Text + myString;
myProcess.Close();
I'm also wondering if it would be possible to allow input from a windows forms control such as a button that would execute a command by entering it in the console and pressing enter for example. Or a textbox that allows you to do the same thing.
Thanks!
You don't need a TextBox control to store a string. Just use a string variable instead.
string concatenatedString = null;
concatenatedString += myStreamReader.ReadToEnd();
Secondly, you can do this without creating a console window. The code below will allow your program to run without seeing a ton of console windows popup.
myProcessStartInfo.CreateNoWindow = true;
Envrionment: .Net 2.0, Windows 2003, 64bit
I am trying to move the website from old server to new server, and below code is not working anymore after moving the codes:
System.Diagnostics.ProcessStartInfo psi = new
System.Diagnostics.ProcessStartInfo("cmd.exe");
psi.UseShellExecute = false;
psi.RedirectStandardOutput = true;
psi.RedirectStandardInput = true;
psi.RedirectStandardError = true;
// Start the process
System.Diagnostics.Process proc = System.Diagnostics.Process.Start(psi);
System.IO.StreamReader strm = proc.StandardError;
System.IO.StreamReader sOut = proc.StandardOutput;
// Attach the in for writing
System.IO.StreamWriter sIn = proc.StandardInput;
sIn.WriteLine(exec);
strm.Close();
sIn.WriteLine("EXIT");
proc.Close();
// Read the sOut to a string.
string results = sOut.ReadToEnd().Trim();
// Close the io Streams;
sIn.Close();
sOut.Close();
It seems as the system does not allow to run none of .exe. The code was working properly on previous server, so I am guessing it is some types of system config issue. I found similar issue on here: Foo.cmd won't output lines in process (on website)
but I did not understand the part "create a new user with privileges to execute batch scripts and select that user as the AppPool user in IIS".I know how to create a new user, but was not able to figure out the way giving a permission to the user to execute .exe or batch files.
Any advice would be helpful.
Thank you,
It could be a .NET Trust level on the new server. Try setting the Trust level in IIS manager to "Full" for that application.
I am running one batch file every few seconds to do timesync with server using following code:
Process process = new Process();
process.StartInfo.WorkingDirectory = Environment.GetFolderPath(Environment.SpecialFolder.System);
process.StartInfo.FileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "cmd.exe");
process.StartInfo.Arguments = #"/C C:\TimeSync.bat";
process.StartInfo.CreateNoWindow = true;
process.StartInfo.UseShellExecute = false;
process.StartInfo.WindowStyle = ProcessWindowStyle.Minimized;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.UserName = "username";
SecureString pwd = new SecureString();
Char[] pwdCharacters = "password".ToCharArray();
foreach (char t in pwdCharacters)
{
pwd.AppendChar(t);
}
process.StartInfo.Password = pwd;
process.Start();
string output = process.StandardOutput.ReadToEnd();
The problem is it flashes the command windows on the screen which I don't want. How can I prevent that?
One behavior I have seen is if I run the same code with UseShellExecute = true and don't provide username and password then the command window doesn't flash.
So basically I want to run .bat file using c# code as different user silently.
Because you are passing a user name and password, the CreateNoWindow parameters are not respected. This is a feature (i.e. bug) in windows. Here's the five year old connect details:
http://connect.microsoft.com/VisualStudio/feedback/details/98476/cmd-windows-shows-using-process-with-createnowindow-when-using-username-password-option
Process.Start() calls advapi32.dll's
CreateProcessWithLogonW in the event
that a user supplies a username and
password, and CreateProcessWithLogonW
always opens a new window.
Unfortunately, there is no workaround
for this behavior
An excellent overview of the create no window option is given here:
http://blogs.msdn.com/b/jmstall/archive/2006/09/28/createnowindow.aspx
which also points out errors in the msdn documentation on this topic.
And there's a very good overview in this stackoverflow answer:
How to hide cmd window while running a batch file?
In the end, I think you want to create a separate little app that you call out to only once, and it runs the whole time, as the escalated user. It can then perform the time sync as often as you want, in the same manner as you've described above, but without having to specify username and password. Thus there will only be one 'flash' of a console window for the entire duration of the application.
Hope this helps
lb
Change your line:
process.StartInfo.WindowStyle = ProcessWindowStyle.Minimized;
to
process.StartInfo.WindowStyle =
ProcessWindowStyle.Hidden;
That will hide the window and never show it.
Hope that helps!
Phil
Did you try to just specify:
process.StartInfo.CreateNoWindow=true;
?
You could use impersonation. I've written an impersonation class that implements the IDisposable interface and is rather straightforward to use, I hope.
Due to the joys of UAC, I need to open an elevated command prompt programmatically and then redirect the standard input so I can use the time command.
I can open the link (a .lnk file) if I use
Process ecp = System.Diagnostics.Process.Start("c:/ecp.lnk");
however, if I use this method, I can't redirect the standardIn.
If I use the StartProcessInformation method (which works wonderfully if you are calling an exe)
ProcessStartInfo processStartInfo = new ProcessStartInfo("c:/ecp.lnk");
processStartInfo.UseShellExecute = false;
processStartInfo.ErrorDialog = false;
processStartInfo.RedirectStandardError = true;
processStartInfo.RedirectStandardInput = true;
processStartInfo.RedirectStandardOutput = true;
Process process = new Process();
process.StartInfo = processStartInfo;
bool processStarted = process.Start();
StreamWriter inp = process.StandardInput;
StreamReader oup = process.StandardOutput;
StreamReader errorReader = process.StandardError;
process.WaitForExit();
I get the error message:
The specified executable is not a valid Win32 application.
Can anyone help me create an elevated command prompt which I can capture the standard input of? Or if anyone knows how to programatically escalate a command prompt?
In case no-one comes up with a better idea (pretty please), here is the work around one of the more devious in my office just came up with:
Copy cmd.exe (the link it pointing at this file)
Paste this file into a different directory
Rename the newly pasted file to something different
Set the permissions on this new file to Run As Administrator
You will still get the escalation dialog popping up, but at least you can capture the standardIn of this valid Win32 app!