C# Winforms and command line batch files - c#

I have this running from my c# winforms app:
string ExecutableFilePath = #"Scripts.bat";
string Arguments = #"";
if (File.Exists(ExecutableFilePath )) {
System.Diagnostics.Process.Start(ExecutableFilePath , Arguments);
}
When that runs I get to see the cmd window until it finishes.
Is there a way to get that to run without showing it to the user?

You should use ProcessStartInfo class and set the following properties
string ExecutableFilePath = #"Scripts.bat";
string Arguments = #"";
if (File.Exists(ExecutableFilePath ))
{
ProcessStartInfo psi = new ProcessStartInfo(ExecutableFilePath , Arguments);
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
Process.Start(psi);
}

Related

How to run sqlite3 inline command using c#?

When I run the below command in cmd prompt of windows:
sqlite3 -header -csv local-DataBase.sqlite "select * from customers;" > data.csv
It creates a file called "data.csv" with the result of "select * from customers;" in it with headers.
I need to run the same command as above in c# so that it the console app creates a file for the result of the sql command.
Till now I have done this:
string sqlLite3ExePath = "sqlite3";
string sqLitePath2 = "-header -csv local-DataBase.sqlite \"select* from customers;\" > data.csv";
using (Process pProcess = new Process())
{
pProcess.StartInfo.FileName = sqlLite3ExePath;
pProcess.StartInfo.Arguments = sqLitePath2 ;
pProcess.StartInfo.UseShellExecute = false;
pProcess.StartInfo.RedirectStandardOutput = true;
pProcess.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
pProcess.StartInfo.CreateNoWindow = false;
pProcess.EnableRaisingEvents = true;
pProcess.Exited += PProcess_Exited;
pProcess.Start();
string output = pProcess.StandardOutput.ReadToEnd();
pProcess.WaitForExit();
Debug.WriteLine(output);
}
But this throws an error:
Error: near ">": syntax error
What am I doing wrong?
As mentioned in the comments, there are two things going on when you run this command from the command prompt, you're running SQLite, but because of the redirect operator, you're also having the shell capture the output and create a file for you.
If you want to recreate this exact behavior, you need to run the shell and pass it this command:
string sqlLite3ExePath = "cmd";
string sqLitePath2 = "/c \"sqlite3 -header -csv local-DataBase.sqlite ^\"select* from customers;^\" > data.csv\"";
using (var pProcess = new Process())
{
pProcess.StartInfo.FileName = sqlLite3ExePath;
pProcess.StartInfo.Arguments = sqLitePath2;
pProcess.StartInfo.UseShellExecute = false;
pProcess.StartInfo.RedirectStandardOutput = true;
pProcess.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
pProcess.StartInfo.CreateNoWindow = false;
pProcess.EnableRaisingEvents = true;
pProcess.Exited += PProcess_Exited;
pProcess.Start();
string output = pProcess.StandardOutput.ReadToEnd();
pProcess.WaitForExit();
Console.WriteLine(output);
}

How to get SVN Commit log using c# Process

I need to get the commit log by date for a svn project using C# application i.e if we have provided the URl , start and end date , we should use the svn.exe in a process to get log details
I have use the command svn log -r {"2007-07-07"}:{2019-11-08} to get the log in command prompt.
SourcePath = args[0]; // URL link
var startDate = args[1];
var endDate = args[2];
var svnSource = args[3]; // svn.exe location in my machine
var cmd1 = "cd /";
var cmd2 = "c:";
var cmd3 = string.Concat("cd ", svnSource);
var cmd4 = string.Concat("svn log ", SourcePath, " -r {", startDate, "}:{", endDate, "}");
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "svn.exe";
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
Process process = new Process();
process.StartInfo = startInfo;
process.Start();
process.StandardInput.WriteLine(cmd1);
process.StandardInput.WriteLine(cmd2);
process.StandardInput.WriteLine(cmd3);
process.StandardInput.WriteLine(cmd4);
while (!process.StandardOutput.EndOfStream)
{
string line = process.StandardOutput.ReadLine();
if (!string.IsNullOrEmpty(line))
{
if (!process.HasExited)
{
}
}
}
I expect the result in the string "line" with all log values but i am getting actual output value as empty. breakpoint does not hit the "while (!process.StandardOutput.EndOfStream)" part itself while debugging.
How to resolve this ? what am i doing wrong here?
First of all, svn.exe will not interpret commands like that, so instead you should start a shell like cmd.exe.
If you're supplying a URL for your SourcePath then svn can run from anywhere from cmd, so you don't need the first 3 commands at all: cmd1, cmd2, cmd3.
That being said, you're not gonna need the svnSource variable either.
Of course, you can cd to the root directory to make your output look cleaner.
So these are the modifications I made to your code:
var SourcePath = args[0]; // URL link
var startDate = args[1];
var endDate = args[2];
var cmd1 = "cd c:\\";
var cmd2 = string.Concat("svn log ", SourcePath, " -r {", startDate, "}:{", endDate, "}");
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "cmd.exe";
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
Process process = new Process();
process.StartInfo = startInfo;
process.Start();
process.StandardInput.WriteLine(cmd1);
process.StandardInput.WriteLine(cmd2);
// It's always a good idea to close your standard input when you're not gonna need it anymore,
// otherwise the process will wait indefinitely for any input and your while condition will never
// be true or in other words it will become an infinite loop...
process.StandardInput.Close();
string result = string.Empty; // for storing the svn commit log
while (!process.StandardOutput.EndOfStream)
{
string line = process.StandardOutput.ReadLine();
if (!string.IsNullOrEmpty(line))
{
if (!process.HasExited)
{
result += line + Environment.NewLine;
}
}
}

How can i execute msg.exe by C# in windows?

Is there a way to display the windows popup msg by using C#?
I mean by using the windows msg.exe program that can be used in cmd, for example:" msg * Hello "
PD: I know that i can use MessageBox.Show() instead. But i want to know if this is possible :(
I wrote 2 ways to do it but none worked:
Process.Start("cmd.exe","/C msg * Hello");
and...
Process cmd = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "cmd.exe",
Arguments = "/C msg * Hello",
UseShellExecute = false,
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden
}
};
cmd.Start();
Did you try adding msg.exe directly?
Process cmd = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = #"msg.exe",
Arguments = #"* /v Hello",
WorkingDirectory = Environment.SystemDirectory;
WindowStyle = ProcessWindowStyle.Normal
}
};
cmd.Start();
I encountered the same problem.
This was because the project was configured as "AnyCPU" but the "Prefer 32-bit" option was checked in the "Build" tab of the project configuration. Uncheck that option and the problem will disappear.
Edit: personnaly, I use the following function to locate the binary according to the executable and OS platform (32/64 bits):
public static bool LocateMsgExe(out string returnedMsgPath)
{
returnedMsgPath = null;
string[] msgPaths = new string[] { Environment.ExpandEnvironmentVariables(#"%windir%\system32\msg.exe"),
Environment.ExpandEnvironmentVariables(#"%windir%\sysnative\msg.exe") };
foreach (string msgPath in msgPaths)
{
if (File.Exists(msgPath))
{
returnedMsgPath = msgPath;
return true;
}
}
return false;
}
And for invoking it :
if (LocateMsgExe(out string strMsgPath))
{
Process.Start(strMsgPath, "* \"Hello world!\"");
}
Regards,
damien.
This is my solution. It consists of a webpage (.aspx) with a listbox (lstComputers), a textbox (txtMessageToSend), a dropdownlist to select the OU that contains the computers that will receive the message and a button (btnSendMessage).
This is the code for btnSendMessage on the aspx.cs
protected void btnSendMessage_Click(object sender, EventArgs e)
{
string searchbase = ddlZaal.SelectedItem.Text; //This is a dropdownlist to select an OU
DirectoryEntry entry = new DirectoryEntry("LDAP://OU=" + searchbase + ",OU=YourOU,OU=YourSubOU," + Variables.Domain + ""); //Variables.Domain is specified in the Web.config
DirectorySearcher mySearcher = new DirectorySearcher(entry);
mySearcher.Filter = ("(objectClass=computer)");
foreach (SearchResult result in mySearcher.FindAll())
{
DirectoryEntry directoryObject = result.GetDirectoryEntry();
string computernaam = directoryObject.Properties["Name"].Value.ToString();
lstComputers.Items.Add(computernaam); //This is a listbox that shows the computernames. To each computer a message is sent.
string pingnaam = computernaam + "dns.suffix"; //Might be necessary for connecting to the computes in the domain
string MessageToSend = txtMessageToSend.Text; //The text in this textbox will be the messagetext
Process process = new Process();
ProcessStartInfo psi = new ProcessStartInfo(#"C:\inetpub\wwwroot\PsExec.exe"); //Location of PsExec.exe on the webserver that hosts the web-application.
psi.UseShellExecute = false;
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
psi.RedirectStandardInput = true;
psi.WindowStyle = ProcessWindowStyle.Minimized;
psi.CreateNoWindow = true;
psi.Arguments = "/accepteula -s -i \\\\" + pingnaam + " cmd /c msg.exe * " + MessageToSend;
process.StartInfo = psi;
process.Start();
}
}

Running exe with parameters doesn't work

var p = Process.Start(#"c:\PsTools\PsExec.exe", #"C:\Windows\System32\notepad.exe");
var err = p.StandardError.ReadToEnd();
var msg = p.StandardOutput.ReadToEnd();
lblStatusResponse.Text = "Err: " + err + "Msg: " + msg;
Why is my code not working?
I getting error:
System.InvalidOperationException: StandardError has not been redirected.
But when I add following:
p.StartInfo.RedirectStandardError = true;
var p = Process.Start(#"c:\PsTools\PsExec.exe", #"C:\Windows\System32\notepad.exe");)
it still gets the same error.
The main problem is that I wanna execute a exe with arguments, but I can't get it to work.
The following code generates a new p, this ignoring the settings you change in the previous instance:
var p = Process.Start(#"c:\PsTools\PsExec.exe", #"C:\Windows\System32\notepad.exe");)
So it doesn't really matter whether you initialize p like this
p.StartInfo.RedirectStandardError = true;
or not.
What you need to do
You need to create a ProcessStartInfo object, configure it and then pass it to Process.Start.
ProcessStartInfo p = new ProcessStartInfo(#"c:\PsTools\PsExec.exe", #"C:\Windows\System32\notepad.exe");
p.UseShellExecute = false;
p.RedirectStandardError = true;
p.RedirectStandardOutput = true;
Process proc = Process.Start(p);
var err = proc.StandardError.ReadToEnd();
var msg = proc.StandardOutput.ReadToEnd();
Taken from MSDN: https://msdn.microsoft.com/en-us/library/system.diagnostics.process.standardoutput(v=vs.110).aspx
The StandardOutput stream has not been defined for redirection; ensure ProcessStartInfo.RedirectStandardOutput is set to true and ProcessStartInfo.UseShellExecute is set to false.
So remember to set those flags as instructed by MS.
Process proc = new Process();
proc.StartInfo.FileName = "cmd.exe";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.Arguments = "/C " + command; //Enter your own command
proc.Start();
string output =proc.StandardOutput.ReadToEnd();
I know this is not the same code you have but this is was the only working code I have , that will run external command/process in C# , and return all of it output/errors to the application main window
public void Processing()
{
//Create and start the ffmpeg process
System.Diagnostics.ProcessStartInfo psi = new ProcessStartInfo("ffmpeg")
{ // this is fully command argument you can make it according to user input
Arguments = "-y -i '/mnt/Disk2/Video/Antina03.jpg' pp.mp4 ",
RedirectStandardOutput = true,
WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
UseShellExecute = false,
RedirectStandardError=true,
RedirectStandardInput=true
};
System.Diagnostics.Process ischk;
ischk = System.Diagnostics.Process.Start(psi);
ischk.WaitForExit();
////Create a streamreader to capture the output of ischk
System.IO.StreamReader ischkout = ischk.StandardOutput;
ischk.WaitForExit();
if (ischk.HasExited) // this condition very important to make asynchronous output
{
string output = ischkout.ReadToEnd();
out0 = output;
}
/// in case you got error message
System.IO.StreamReader iserror = ischk.StandardError;
ischk.WaitForExit();
if (ischk.HasExited)
{
string output = iserror.ReadToEnd();
out0 = output;
}
}
if you want to run this process just call the function Processing() BTW out0 are global variable so it can use out the function .
credit
I'm using MonoDevlop "C# devloping tool on Linux " and I get the output this way :-
public MainWindow() : base(Gtk.WindowType.Toplevel)
{
Build();
Processing();
textview2.Buffer.Text = out0;
}

How to execute commands in Command Prompt using c#

I want to execute these steps in CMD using c#
1 - CD C:\MySQL\MySQL Server 5.0\bin
2 - mysqldump -uroot -ppassword sample> d:\Test\222.sql
On manually doing this, i will get file named "222.sql"
I am using the below code to do it, but missing something.. Nothing Happens
public void CreateScript_AAR()
{
string commandLine = #"CD C:\MySQL\MySQL Server 5.0\bin\mysqldump -uroot -ppassword sample> d:\Test\222.sql""";
System.Diagnostics.ProcessStartInfo PSI = new System.Diagnostics.ProcessStartInfo("cmd.exe");
PSI.RedirectStandardInput = true;
PSI.RedirectStandardOutput = true;
PSI.RedirectStandardError = true;
PSI.UseShellExecute = false;
System.Diagnostics.Process p = System.Diagnostics.Process.Start(PSI);
System.IO.StreamWriter SW = p.StandardInput;
System.IO.StreamReader SR = p.StandardOutput;
SW.WriteLine(commandLine);
SW.Close();
}
You're executing both commands in 1 command, this is not valid syntax.
You don't even need to change the directory, so just remove the dirchange (CD) from your command string. Also, use quotes like Oded said.
string commandLine = #"""C:\MySQL\MySQL Server 5.0\bin\mysqldump"" -uroot -ppassword sample > d:\Test\222.sql";
You can also call MySqlDump.exe directly from your code without cmd.exe. Capture its output and write it to a file. Writing it in the correct encoding is important so that it restores correctly.
string binary = #"C:\MySQL\MySQL Server 5.0\bin\mysqldump.exe"
string arguments = #"-uroot -ppassword sample"
System.Diagnostics.ProcessStartInfo PSI = new System.Diagnostics.ProcessStartInfo(binary, arguments);
PSI.RedirectStandardInput = true;
PSI.RedirectStandardOutput = true;
PSI.RedirectStandardError = true;
PSI.UseShellExecute = false;
System.Diagnostics.Process p = System.Diagnostics.Process.Start(PSI);
Encoding encoding = p.StandardOutput.CurrentEncoding;
System.IO.StreamWriter SW = new StreamWriter(#"d:\Test\222.sql", false, encoding);
p.WaitOnExit();
string output = p.StandardOutput.ReadToEnd()
SW.Write(output)
SW.Close();
This is how I used it to meet my requirements.
public static void runResGen()
{
string ResGen = #"C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools\ResGen.exe";
string outputPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\resxMerge";
DirectoryInfo dinfo = new DirectoryInfo(outputPath);
DirectoryInfo latestdir = dinfo.GetDirectories().OrderByDescending(f => f.CreationTime).FirstOrDefault();
string latestDirectory = latestdir.FullName.ToString();
string arguments = latestDirectory + "\\StringResources.resx /str:c#,,StringResources /publicClass";
ProcessStartInfo PSI = new ProcessStartInfo(ResGen, arguments);
PSI.RedirectStandardInput = true;
PSI.RedirectStandardOutput = true;
PSI.RedirectStandardError = true;
PSI.UseShellExecute = false;
PSI.CreateNoWindow = true;
System.Diagnostics.Process p = System.Diagnostics.Process.Start(PSI);
Encoding encoding = p.StandardOutput.CurrentEncoding;
p.Close();
}

Categories