Integrate bat files in windows form app - c#

I want to make a windows form app in which with the press of a button will execute the commands of a bat file, but i do not want to have the bat file stored.

You could potentially do one of 2 things.
Create the file in a temp space. execute the cmd using process.start. and delete after its execution. you should wait for the command to end.
or you could open cmd with stdin and write the commands to the cmd.
public static string Execute(string file, params string[] args)
{
string argpass = "";
foreach (string arg in args)
argpass += "\"" + arg + "\" ";
var info = new ProcessStartInfo();
info.FileName = file;
info.Arguments = argpass;
info.UseShellExecute = false;
info.RedirectStandardOutput = true;
var p = Process.Start(info);
p.WaitForExit();
return p.StandardOutput.ReadToEnd();
}
Some think like this using the command
File.WriteAllText("TempScript.bat","batch data");
string outp = Execute(cmd,"TempScript.bat");
File.Delete("TempScript.bat");

Related

How to create a command line to run c# exe file and give some parameters to a function in form1?

I have c# program that I want to run but from the cmd using a command line so here is my question I don't know how to create the command and I don't know how to send the parameter in my command to some function there.
You can use the Process class to execute files
var fileName = "some.exe";
var arguments = "";
var info = new System.Diagnostics.ProcessStartInfo(fileName, arguments);
info.UseShellExecute = false;
info.CreateNoWindow = true;
// if you want read output
info.RedirectStandardOutput = true;
var process = new System.Diagnostics.Process { StartInfo = info };
process.Start();
var output = process.StandardOutput.ReadToEnd();
var error = process.StandardError?.ReadToEnd();
You can create a console application and after generating (by building) .exe file, you can call with the arguments in command line.
Sample Example:
class Program
{
static void Main(string[] args)
{
var a = Convert.ToInt32(args[0]);
var b = Convert.ToInt32(args[1]);
Console.WriteLine(a+b);
}
}
OUTPUT

How to send multiple files to the printer with one Process call

I need to print multiple PDF-files from the hard-drive. I have found this beautiful solution of how to send a file to the printer. The problem with this solution is that if you want to print multiple files you have to wait for each file for the process to finish.
in the command shell it is possible to use the same command with multiple filenames: print /D:printerName file1.pdf file2.pdf
and one call would print them all.
unfortunately simply just to put all the filenames into the ProcessStartInfo doesn't work
string filenames = #"file1.pdf file2.pdf file3.pdf"
ProcessStartInfo info = new ProcessStartInfo();
info.Verb = "print";
info.FileName = filenames;
neither does it to put the filenames as Arguments of the Process
info.Arguments = filename;
I always get the error: Cannot find the file!
How can I print a multitude of files with one process call?
Here is an example of how I use it now:
public void printWithPrinter(string filename, string printerName)
{
var procInfo = new ProcessStartInfo();
// the file name is a string of multiple filenames separated by space
procInfo.FileName = filename;
procInfo.Verb = "printto";
procInfo.WindowStyle = ProcessWindowStyle.Hidden;
procInfo.CreateNoWindow = true;
// select the printer
procInfo.Arguments = "\"" + printerName + "\"";
// doesn't work
//procInfo.Arguments = "\"" + printerName + "\"" + " " + filename;
Process p = new Process();
p.StartInfo = procInfo;
p.Start();
p.WaitForInputIdle();
//Thread.Sleep(3000;)
if (!p.CloseMainWindow()) p.Kill();
}
Following should work:
public void PrintFiles(string printerName, params string[] fileNames)
{
var files = String.Join(" ", fileNames);
var command = String.Format("/C print /D:{0} {1}", printerName, files);
var process = new Process();
var startInfo = new ProcessStartInfo
{
WindowStyle = ProcessWindowStyle.Hidden,
FileName = "cmd.exe",
Arguments = command
};
process.StartInfo = startInfo;
process.Start();
}
//CALL
PrintFiles("YourPrinterName", "file1.pdf", "file2.pdf", "file3.pdf");
It's not necessarily a simple solution, but you could merge the pdfs first and then send then to acrobat.
For example, use PdfMerge
Example overload to your initial method:
public void printWithPrinter(string[] fileNames, string printerName)
{
var fileStreams = fileNames
.Select(fileName => (Stream)File.OpenRead(fileName)).ToList();
var bundleFileName = Path.GetTempPath();
try
{
try
{
var bundleBytes = new PdfMerge.PdfMerge().MergeFiles(fileStreams);
using (var bundleStream = File.OpenWrite(bundleFileName))
{
bundleStream.Write(bundleBytes, 0, bundleBytes.Length);
}
}
finally
{
fileStreams.ForEach(s => s.Dispose());
}
printWithPrinter(bundleFileName, printerName);
}
finally
{
if (File.Exists(bundleFileName))
File.Delete(bundleFileName);
}
}

C# CMD with command not executed [duplicate]

In C# WPF: I want to execute a CMD command, how exactly can I execute a cmd command programmatically?
Here's a simple example :
Process.Start("cmd","/C copy c:\\file.txt lpt1");
As mentioned by the other answers you can use:
Process.Start("notepad somefile.txt");
However, there is another way.
You can instance a Process object and call the Start instance method:
Process process = new Process();
process.StartInfo.FileName = "notepad.exe";
process.StartInfo.WorkingDirectory = "c:\temp";
process.StartInfo.Arguments = "somefile.txt";
process.Start();
Doing it this way allows you to configure more options before starting the process. The Process object also allows you to retrieve information about the process whilst it is executing and it will give you a notification (via the Exited event) when the process has finished.
Addition: Don't forget to set 'process.EnableRaisingEvents' to 'true' if you want to hook the 'Exited' event.
if you want to start application with cmd use this code:
string YourApplicationPath = "C:\\Program Files\\App\\MyApp.exe"
ProcessStartInfo processInfo = new ProcessStartInfo();
processInfo.WindowStyle = ProcessWindowStyle.Hidden;
processInfo.FileName = "cmd.exe";
processInfo.WorkingDirectory = Path.GetDirectoryName(YourApplicationPath);
processInfo.Arguments = "/c START " + Path.GetFileName(YourApplicationPath);
Process.Start(processInfo);
Using Process.Start:
using System.Diagnostics;
class Program
{
static void Main()
{
Process.Start("example.txt");
}
}
How about you creat a batch file with the command you want, and call it with Process.Start
dir.bat content:
dir
then call:
Process.Start("dir.bat");
Will call the bat file and execute the dir
You can use this to work cmd in C#:
ProcessStartInfo proStart = new ProcessStartInfo();
Process pro = new Process();
proStart.FileName = "cmd.exe";
proStart.WorkingDirectory = #"D:\...";
string arg = "/c your_argument";
proStart.Arguments = arg;
proStart.WindowStyle = ProcessWindowStyle.Hidden;
pro.StartInfo = pro;
pro.Start();
Don't forget to write /c before your argument !!
Argh :D not the fastest
Process.Start("notepad C:\test.txt");
Are you asking how to bring up a command windows? If so, you can use the Process object ...
Process.Start("cmd");
You can do like below:
var command = "Put your command here";
System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
procStartInfo.WorkingDirectory = #"C:\Program Files\IIS\Microsoft Web Deploy V3";
procStartInfo.CreateNoWindow = true; //whether you want to display the command window
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
string result = proc.StandardOutput.ReadToEnd();
label1.Text = result.ToString();
In addition to the answers above, you could use a small extension method:
public static class Extensions
{
public static void Run(this string fileName,
string workingDir=null, params string[] arguments)
{
using (var p = new Process())
{
var args = p.StartInfo;
args.FileName = fileName;
if (workingDir!=null) args.WorkingDirectory = workingDir;
if (arguments != null && arguments.Any())
args.Arguments = string.Join(" ", arguments).Trim();
else if (fileName.ToLowerInvariant() == "explorer")
args.Arguments = args.WorkingDirectory;
p.Start();
}
}
}
and use it like so:
// open explorer window with given path
"Explorer".Run(path);
// open a shell (remanins open)
"cmd".Run(path, "/K");

How to start kdiff from Console application?

UPDATED...
I want to call kdiff from Console application. So I'm building two files and want to compare they at the end of executing my program:
string diffCmd = string.Format("{0} {1}", Logging.FileNames[0], Logging.FileNames[1]);
// diffCmd = D:\vdenisenko\DbHelper\DbHelper\bin\Debug\Reports\16_Nov 06_30_46_DiscussionThreads_ORIGIN.txt D:\vdenisenko\DbHelper\DbHelper\bin\Debug\Reports\16_Nov 06_30_46_DiscussionThreads_ORIGIN.txt
System.Diagnostics.Process.Start(#"C:\Program Files (x86)\KDiff3\kdiff3.exe", diffCmd);
//specification is here http://kdiff3.sourceforge.net/doc/documentation.html
It runs kdiff3 tool, but something wrong with filenames or command... Could you please look on screenshot and say what is wrong?
You need to use Process.Start():
string kdiffPath = #"c:\Program Files\Kdiff3.exe"; // here is full path to kdiff utility
string fileName = #"d:\file1.txt";
string fileName2 = #"d:\file2.txt";
Process.Start(kdiffPath,String.Format("\"{0}\" \"{1}\"",fileName,fileName2));
Arguments as described in the docs: kdiff3 file1 file2
var args = String.Format("{0} {1}", fileName, fileName2);
Process.Start(kdiffPath, args);
string kdiffPath = #"c:\Program Files\Kdiff3.exe"; // here is full path to kdiff utility
string fileName = #"d:\file1.txt";
string fileName2 = #"d:\file2.txt";
ProcessStartInfo psi = new ProcessStartInfo(kdiffPath);
psi.RedirectStandardOutput = true;
psi.WindowStyle = ProcessWindowStyle.Hidden;
psi.UseShellExecute = false;
psi.Arguments = fileName + " " + fileName2;
Process app = Process.Start(psi);
StreamReader reader = app.StandardOutput;
//get reponse from console app in your app
do
{
string line = reader.ReadLine();
}
while(!reader.EndOfStream);
app.WaitForExit();
This will run the program from your console app
Process p = new Process();
p.StartInfo.FileName = kdiffPath;
p.StartInfo.Arguments = "\"" + fileName + "\" \"" + fileName2 + "\"";
p.Start();
Unless you are trying to do something else, in which case you need to provide more details.

Execute command line using C#

All I am trying to do is send a command that opens a model with the program.exe
Supposed to be super simple!
Ex:
"C:\Program Files (x86)\River Logic\Enterprise Optimizer 7.4 Developer\EO74.exe" "C:\PauloXLS\Constraint Sets_1.cor"
The line above works well if pasted on the command prompt window.
However, when trying to pass the same exact string on my code it gets stuck on C:\Program
string EXE = "\"" + #tbx_base_exe.Text.Trim() + "\"";
string Model = "\"" + #mdl_path.Trim()+ "\"";
string ExeModel = EXE + " " + Model;
MessageBox.Show(ExeModel);
ExecuteCommand(ExeModel);
ExeModel is showing te following line on Visual Studio:
"\"C:\\Program Files (x86)\\River Logic\\Enterprise Optimizer 7.4 Developer\\EO74.exe\" \"C:\\PauloXLS\\Constraint Sets_1.cor\""
To me looks like it is the string I need to send in to the following method:
public int ExecuteCommand(string Command)
{
int ExitCode;
ProcessStartInfo ProcessInfo;
Process Process;
ProcessInfo = new ProcessStartInfo("cmd.exe", "/K " + Command);
ProcessInfo.CreateNoWindow = true;
ProcessInfo.UseShellExecute = true;
Process = Process.Start(ProcessInfo);
Process.WaitForExit();
ExitCode = Process.ExitCode;
Process.Close();
return ExitCode;
}
Things I've tried:
Pass only one command at a time (works as expected), but not an option since the model file will open with another version of the software.
Tried to Trim
Tried with # with \"
Can anyone see any obvious mistake? Thanks.
It's pretty straightforward. You just create a command line object then write to it, then to execute it you read back from it using SR.ReadToEnd():
private string GETCMD()
{
string tempGETCMD = null;
Process CMDprocess = new Process();
System.Diagnostics.ProcessStartInfo StartInfo = new System.Diagnostics.ProcessStartInfo();
StartInfo.FileName = "cmd"; //starts cmd window
StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
StartInfo.CreateNoWindow = true;
StartInfo.RedirectStandardInput = true;
StartInfo.RedirectStandardOutput = true;
StartInfo.UseShellExecute = false; //required to redirect
CMDprocess.StartInfo = StartInfo;
CMDprocess.Start();
System.IO.StreamReader SR = CMDprocess.StandardOutput;
System.IO.StreamWriter SW = CMDprocess.StandardInput;
SW.WriteLine("#echo on");
SW.WriteLine("cd\\"); //the command you wish to run.....
SW.WriteLine("cd C:\\Program Files");
//insert your other commands here
SW.WriteLine("exit"); //exits command prompt window
tempGETCMD = SR.ReadToEnd(); //returns results of the command window
SW.Close();
SR.Close();
return tempGETCMD;
}
Why are you opening a command prompt (cmd.exe)? Just pass the name of the executable.

Categories

Resources