Cmd with c# console app, does these commands work? - c#

Well... everything is in the title, this is a C# console app and i'm trying to execute these commands... it dosen't seems to work but why ?
It just open a cmd, i don't see anything like a command
static void Main(string[] args)
{
string strCmdText = "mysqlcheck -r JAMFSOFTWARE -u root -p password";
System.Diagnostics.Process.Start("CMD.exe", strCmdText);
string strCmdText2 = "mysqlcheck -o JAMFSOFTWARE -u root -p password";
System.Diagnostics.Process.Start("CMD.exe", strCmdText);
string strCmdText3 = "mysqlcheck -c JAMFSOFTWARE -u root -p password";
System.Diagnostics.Process.Start("CMD.exe", strCmdText);
}
Edit : The thing is i don't want to put that password in a batch file where it would be easely accessible, so basically any solution would do as long as no one can see what's in the commande file
GOT CLOSER TO A SOLUTION :
static void Main(string[] args)
{
ProcessStartInfo startInfo = new ProcessStartInfo("mysqlcheck");
startInfo.Arguments = "-c JAMFSOFTWARE -u root -p !!fakepassword!!";
Process process = new Process();
process.StartInfo = startInfo;
process.OutputDataReceived += new DataReceivedEventHandler(process_OutputDataReceived);
try
{
process.Start();
}
catch
{
}
}
static void process_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
StreamWriter sw = new StreamWriter("C:\\JAMFCHECK.txt");
sw.WriteLine( e.Data);
}
now i don't know why but it ask for a password...

based on your comment, I think you don't need CMD
you can start the 'mysqlcheck' directly using a different executable (see below)
to get all the results from the command-line can be a bit tricky.
I added a working sample at the end of the answer but I'd like to explain it a bit.
set up what you want to execute first
FileInfo executable = new FileInfo(#"C:\Temp\cmd.bat");
ProcessStartInfo startInfo = new ProcessStartInfo(executable.FullName);
startInfo.Arguments = "two arguments";
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
startInfo.RedirectStandardOutput = true;
make sure to redirect the output (also I don't want to see it)
Now you give your StartInfo to the process
Process process = new Process();
process.StartInfo = startInfo;
because we want to read the Output we need to
process.EnableRaisingEvents = true;
I assigned two events:
process.OutputDataReceived += new ...
process.Exited += new ...
start the process and start reading
process.Start();
process.BeginOutputReadLine();
The batchFile I used gave me the file and the arguments
#echo off
echo %~nx0
echo %1
echo %2
you can call any executable like this (except cmd.exe, it never finishes)
I attached the complete code and also added a Reset-Event to sync the execution. Here is the output from my debug-console:
Beginn
Starting external Application: C:\Temp\cmd.bat
cmd.bat
two
arguments
Finished executing external Application
End
listing:
// using System.Diagnostics;
// using System.Threading;
// using System.IO
private ManualResetEvent mre;
private void button_Click(object sender, EventArgs e)
{
mre = new ManualResetEvent(false);
Debug.WriteLine("Beginn");
FileInfo executable = new FileInfo(#"C:\Temp\cmd.bat");
ProcessStartInfo startInfo = new ProcessStartInfo(executable.FullName);
startInfo.Arguments = "two arguments";
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
startInfo.RedirectStandardOutput = true;
Process process = new Process();
process.EnableRaisingEvents = true;
process.StartInfo = startInfo;
process.OutputDataReceived += new DataReceivedEventHandler(process_OutputDataReceived);
process.Exited += new EventHandler(process_Exited);
Debug.WriteLine(String.Format("Starting external Application: {0}", executable.FullName));
process.Start();
process.BeginOutputReadLine();
mre.WaitOne();
Debug.WriteLine("End");
}
void process_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
Debug.WriteLine(e.Data);
}
void process_Exited(object sender, EventArgs e)
{
Debug.WriteLine("Finished executing external Application");
mre.Set();
}
hope it helps, best regards

You need to start strCmdText with /C:
static void Main(string[] args)
{
string strCmdText = "/C mysqlcheck -r JAMFSOFTWARE -u root -p password";
System.Diagnostics.Process.Start("CMD.exe", strCmdText);
string strCmdText2 = "/C mysqlcheck -o JAMFSOFTWARE -u root -p password";
System.Diagnostics.Process.Start("CMD.exe", strCmdText);
string strCmdText3 = "/C mysqlcheck -c JAMFSOFTWARE -u root -p password";
System.Diagnostics.Process.Start("CMD.exe", strCmdText);
}

Related

C# Running command prompt as admin

I'm trying to run a few lines of command in an attempt to automate a work process. I've done some research online to get an idea of what I need to do. However the file remains unaffected. When I run the same command through admin command prompt, the command works.
Commands:
echo 127.0.0.1 webedit.egnyte.com >> "C:\Windows\System32\drivers\etc\hosts"
"%ProgramFiles(x86)%\Egnyte Connect\EgnyteDrive.exe" -command add -l Egnyte -d seagen -sso use-sso -t U -c connect_immediately
I've changed the manifest to "requireAdministrator" and "highestAvailable". However there still is no change to the file.
private void Button1_Click(object sender, EventArgs e)
{
string command1 = "echo 127.0.0.1 webedit.egnyte.com >> \"C:\\Windows\\System32\\drivers\\etc\\hosts\"";
Console.WriteLine("Starting Command 1: " + command1);
Process process = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = command1;
startInfo.UseShellExecute = true;
startInfo.Verb = "runas";
process.StartInfo = startInfo;
process.Start();
Console.WriteLine("Completed Command 1 ");
}
The file "host" should have an added line to it.

Run "ping" command when link button is clicked

I am trying to pop up a Windows Command prompt and run a ping command when a link button is clicked. Link button looks something like:
<asp:LinkButton runat="server" ID="lbFTPIP" OnCommand="lbFTPIP_OnCommand" CommandArgumnet="1.2.3.4" Text="1.2.3.4"/>
I tried this for OnCommand:
protected void lbFTPIP_OnCommand(object sender, CommandEventArgs e)
{
string sFTPIP = e.CommandArgument.ToString();
string sCmdText = #"ping -a " + sFTPIP;
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = sCmdText;
p.StartInfo.RedirectStandardOutput = false;
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = false;
p.Start();
}
When I click the link, it opens the command prompt but does not display or execute the command, it just shows the current directory. Not sure what I am missing here.
It is part of a web page, if this makes a difference.
In order to open a console and immediately run a command, you need to use either the /C or /K switch:
// Will run the command and then close the console.
string sCmdText = #"/C ping -a " + sFTPIP;
// Will run the command and keep the console open.
string sCmdText = #"/K ping -a " + sFTPIP;
If you want to institute a "Press any key", you can add a PAUSE:
// Will run the command, wait for the user press a key, and then close the console.
string sCmdText = #"/C ping -a " + sFTPIP + " & PAUSE";
EDIT:
It would probably be best to redirect your output and then display the results separately:
Process p = new Process();
// No need to use the CMD processor - just call ping directly.
p.StartInfo.FileName = "ping.exe";
p.StartInfo.Arguments = "-a " + sFTPIP;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = false;
p.Start();
p.WaitForExit();
var output = p.StandardOutput.ReadToEnd();
// Do something the output.
You don't need to execute cmd.exe, just execute ping.exe instead.
string sCmdText = #"-a " + sFTPIP;
Process p = new Process();
p.StartInfo.FileName = "ping.exe";
p.StartInfo.Arguments = sCmdText;
p.StartInfo.RedirectStandardOutput = false;
p.StartInfo.UseShellExecute = true;
p.StartInfo.CreateNoWindow = false;
p.Start();
Also, don't set UseShellExecute = false unless you intend to redirect the output, which I'm surprised you are not doing.
First thing is that you have something strange here CommandArgumnet="1.2.3.4" that is misspelled. The other thing is the /C and a space before ping.

How to hide the Command Window using c#

Building a console app that will execute an exe file(pagesnap.exe). I would like to hide its window(pagesnap.exe) during execution. How is it done.
ProcessStartInfo Psi = new ProcessStartInfo("D:\\PsTools\\");
Psi.FileName = "D:\\PsTools\\psexec.exe";
Psi.Arguments = #"/C \\DESK123 D:\files\pagesnap.exe";
Psi.UseShellExecute = false;
Psi.RedirectStandardOutput = true;
Psi.RedirectStandardInput = true;
Psi.WindowStyle = ProcessWindowStyle.Hidden;
Psi.CreateNoWindow = true;
Process.Start(Psi).WaitForExit();
DESK123 is the local PC. Would later try this with remote PCs.
Things I have tried
Psi.Arguments = #"/C start /b psexec \\DESK123 D:\files\pagesnap.exe";
Psi.Arguments = #"/b psexec \\DESK123 D:\files\pagesnap.exe";
Psi.Arguments = #"/C psexec \\DESK123 /b D:\files\pagesnap.exe";
Psi.Arguments = #"/C psexec \\DESK123 D:\files\pagesnap.exe 2>&1 output.log";
Update: I have built pagesnap with Output type as a windows application instead of console. The cmd window doesn't come up, now. Seems this is the only way for me
Simply call the following function. Pass the argument as your command and your working directory
private string BatchCommand(string cmd, string mapD)
{
System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + cmd);
procStartInfo.WorkingDirectory = mapD;
// The following commands are needed to redirect the standard output.
// This means that it will be redirected to the Process.StandardOutput StreamReader.
procStartInfo.RedirectStandardOutput = true;
procStartInfo.RedirectStandardError = true;
procStartInfo.RedirectStandardInput = true;
procStartInfo.UseShellExecute = false;
// Do not create the black window.
procStartInfo.CreateNoWindow = true;
// Now we create a process, assign its ProcessStartInfo and start it
System.Diagnostics.Process cmdProcess = new System.Diagnostics.Process();
cmdProcess.StartInfo = procStartInfo;
cmdProcess.ErrorDataReceived += cmd_Error;
cmdProcess.OutputDataReceived += cmd_DataReceived;
cmdProcess.EnableRaisingEvents = true;
cmdProcess.Start();
cmdProcess.BeginOutputReadLine();
cmdProcess.BeginErrorReadLine();
cmdProcess.StandardInput.WriteLine("ping www.google.com"); //Execute ping
cmdProcess.StandardInput.WriteLine("exit"); //Execute exit.
cmdProcess.WaitForExit();
// Get the output into a string
return Batchresults;
}
static void cmd_DataReceived(object sender, DataReceivedEventArgs e)
{
if (e.Data != null)
Batchresults += Environment.NewLine + e.Data.ToString();
}
void cmd_Error(object sender, DataReceivedEventArgs e)
{
if (e.Data != null)
{
Batchresults += Environment.NewLine + e.Data.ToString();
}
}

C# get process output while running

Is there anyway to redirect standard output of a spawned process and capture it as its happening. Everything I have seen just does a ReadToEnd after the process has finished. I would like to be able to get the output as it is being printed.
Edit:
private void ConvertToMPEG()
{
// Start the child process.
Process p = new Process();
// Redirect the output stream of the child process.
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
//Setup filename and arguments
p.StartInfo.Arguments = String.Format("-y -i \"{0}\" -target ntsc-dvd -sameq -s 720x480 \"{1}\"", tempDir + "out.avi", tempDir + "out.mpg");
p.StartInfo.FileName = "ffmpeg.exe";
//Handle data received
p.OutputDataReceived += new DataReceivedEventHandler(p_OutputDataReceived);
p.Start();
}
void p_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
Debug.WriteLine(e.Data);
}
Use Process.OutputDataReceived event from the process, to recieve the data you need.
Example:
var myProc= new Process();
...
myProc.StartInfo.RedirectStandardOutput = true;
myProc.OutputDataReceived += new DataReceivedEventHandler(MyProcOutputHandler);
...
private static void MyProcOutputHandler(object sendingProcess,
DataReceivedEventArgs outLine)
{
// Collect the sort command output.
if (!String.IsNullOrEmpty(outLine.Data))
{
....
}
}
So after a little more digging I found out that ffmpeg uses stderr for output. Here is my modified code to get the output.
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.Arguments = String.Format("-y -i \"{0}\" -target ntsc-dvd -sameq -s 720x480 \"{1}\"", tempDir + "out.avi", tempDir + "out.mpg");
p.StartInfo.FileName = "ffmpeg.exe";
p.ErrorDataReceived += new DataReceivedEventHandler(p_ErrorDataReceived);
p.OutputDataReceived += new DataReceivedEventHandler(p_OutputDataReceived);
p.Start();
p.BeginErrorReadLine();
p.WaitForExit();

Silent installation

I am writing a InstallerClass using C# as a custom action for my installer, and I can successfully run an external exe (installation) using the InstallerClass, but when I try to use /quiet in the InstallerClass, it does not install the exe. But I can successfully install this in silent mode using /quiet in the command prompt.
Is there any reason for this or otherwise how to install in silent mode using C#?
Following is the code I use within the Commit method (overriden):
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.FileName = pathExternalInstaller;
p.StartInfo.Arguments = "/quiet";
p.Start();
Here is what I use to do a quiet Install and Uninstall:
public static bool RunInstallMSI(string sMSIPath)
{
try
{
Console.WriteLine("Starting to install application");
Process process = new Process();
process.StartInfo.FileName = "msiexec.exe";
process.StartInfo.Arguments = string.Format(" /qb /i \"{0}\" ALLUSERS=1", sMSIPath);
process.Start();
process.WaitForExit();
Console.WriteLine("Application installed successfully!");
return true; //Return True if process ended successfully
}
catch
{
Console.WriteLine("There was a problem installing the application!");
return false; //Return False if process ended unsuccessfully
}
}
public static bool RunUninstallMSI(string guid)
{
try
{
Console.WriteLine("Starting to uninstall application");
ProcessStartInfo startInfo = new ProcessStartInfo("cmd.exe", string.Format("/c start /MIN /wait msiexec.exe /x {0} /quiet", guid));
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
Process process = Process.Start(startInfo);
process.WaitForExit();
Console.WriteLine("Application uninstalled successfully!");
return true; //Return True if process ended successfully
}
catch
{
Console.WriteLine("There was a problem uninstalling the application!");
return false; //Return False if process ended unsuccessfully
}
}
This works for me.
Process process = new Process();
process.StartInfo.FileName = # "C:\PATH\Setup.exe";
process.StartInfo.Arguments = "/quiet";
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
process.Start();
process.WaitForExit();
Have you tried using the /Q or /QB parameter that is listed in the Installation parameters? It might look something like this:
p.StartInfo.Arguments = "/Q";
I got that out of this document: http://msdn.microsoft.com/en-us/library/ms144259(v=sql.100).aspx
Here is my logic to silent install an app for all users:
public void Install(string filePath)
{
try
{
Process process = new Process();
{
process.StartInfo.FileName = filePath;
process.StartInfo.Arguments = " /qb ALLUSERS=1";
process.EnableRaisingEvents = true;
process.Exited += process_Exited;
process.Start();
process.WaitForExit();
}
}
catch (InvalidOperationException iex)
{
Interaction.MsgBox(iex.Message, MsgBoxStyle.OkOnly, MethodBase.GetCurrentMethod().Name);
}
catch (Exception ex)
{
Interaction.MsgBox(ex.Message, MsgBoxStyle.OkOnly, MethodBase.GetCurrentMethod().Name);
}
}
private void process_Exited(object sender, EventArgs e)
{
var myProcess = (Process)sender;
if (myProcess.ExitCode == 0)
// do yours here...
}
string filePath = #"C:\Temp\Something.msi";
Process.Start(filePath, #"/quiet").WaitForExit();
It worked for me.

Categories

Resources