Display Batch output in TextBox - c#

I have tried to run the batch file from c# using the following code and i want to display the result in WPF textbox. Could you please guide me how to do this?
using System;
namespace Learn
{
class cmdShell
{
[STAThread] // Lets main know that multiple threads are involved.
static void Main(string[] args)
{
System.Diagnostics.Process proc; // Declare New Process
proc = System.Diagnostics.Process.Start("C:\\listfiles.bat"); // run test.bat from command line.
proc.WaitForExit(); // Waits for the process to end.
}
}
}
This batch file is to list the files from the folder. Once the batch is executed result should be displayed in the textbox. If the batch file having more than one commands, then result of each commands should be displayed in textbox.

You need to redirect the standard output stream:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
namespace Test
{
class Program
{
static void Main(string[] args)
{
Process proc = new Process();
proc.StartInfo.FileName = "test.bat";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.Start();
string output = proc.StandardOutput.ReadToEnd();
Console.WriteLine(output); // or do something else with the output
proc.WaitForExit();
Console.ReadKey();
}
}
}

I have resolved the issues with process hanging and getting output instantly as below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
namespace Test
{
class Program
{
static void Main(string[] args)
{
Process proc = new Process();
proc.StartInfo.FileName = "test.bat";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.OutputDataReceived += proc_OutputDataReceived;
proc.Start();
proc.BeginOutputReadLine();
}
}
void proc_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
this.Dispatcher.Invoke((Action)(() =>
{
txtprogress.Text = txtprogress.Text + "\n" + e.Data;
txtprogress.ScrollToEnd();
}));
}
}

Related

output of a process not getting printed

I am trying to print the output of my process as it runs,I used https://msdn.microsoft.com/en-us/library/system.diagnostics.process.beginerrorreadline(v=vs.110).aspx as reference,I cant figure out why it cant print the output,can anyone tell me why the stdout is not getting printed for the following code?
using System;
using System.IO;
using System.Diagnostics;
using System.Text;
using System.Text.RegularExpressions;
namespace stdout_save
{
class Program
{
private static StringBuilder netOutput = null;
private static void NetOutputDataHandler(object sendingProcess,
DataReceivedEventArgs outLine)
{
// Collect the net view command output.
if (!String.IsNullOrEmpty(outLine.Data))
{
// Add the text to the collected output.
netOutput.Append(Environment.NewLine + " " + outLine.Data);
}
}
static void Main(string[] args)
{
string python = #"C:\\Python27\python.exe";
// python app to call
string myPythonApp = #"C:\\tools\tool.py";
ProcessStartInfo myProcessStartInfo = new ProcessStartInfo(python);
myProcessStartInfo.UseShellExecute = false;
myProcessStartInfo.RedirectStandardOutput = true;
myProcessStartInfo.RedirectStandardError = true;
// start python app with arguments
myProcessStartInfo.Arguments = String.Format("{0}", myPythonApp);
Process myProcess = new Process();
myProcess.StartInfo = myProcessStartInfo;
myProcess.OutputDataReceived += new DataReceivedEventHandler(NetOutputDataHandler);
netOutput = new StringBuilder();
myProcess.Start();
myProcess.BeginOutputReadLine();
Console.WriteLine(netOutput);
myProcess.WaitForExit();
myProcess.Close();
Console.ReadLine();
}
}
}
You're writing the output before it has a chance to be captured, swap the two lines and it should work:
// Wait for the process to exit first
myProcess.WaitForExit();
// The dump it's output
Console.WriteLine(netOutput);
Edit:
Or, if you need to output it while the command is being run, perform your output in the OutputDataReceived handler:
private static void NetOutputDataHandler(object sendingProcess,
DataReceivedEventArgs outLine)
{
// Collect the net view command output.
if (!String.IsNullOrEmpty(outLine.Data))
{
// Add the text to the collected output.
netOutput.Append(Environment.NewLine + " " + outLine.Data);
// And output it as it's sent
Console.WriteLine(outLine.Data);
}
}

How to execute a scheduled task with “schtasks” without opening a new command line window using C# process?

I am trying to run a scheduled task from C# without opening a new command line window, using the following code without any success (it prompts a window every time I use it)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
try
{
Process p1 = new Process();
p1.StartInfo.FileName = #"C:\Windows\System32\schtasks.exe";
p1.StartInfo.Verb = "runas";
p1.StartInfo.Arguments = "/run /tn CCleaner";
p1.StartInfo.RedirectStandardOutput = true;
p1.StartInfo.UseShellExecute = false;
p1.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p1.StartInfo.CreateNoWindow = true;
p1.Start();
p1.Close();
}
catch (Exception ex)
{
}
}
}
}
How could I solve this problem ?
Thank you so much for your attention
You can use a library that provides access to Task Scheduler API.
For example using http://taskscheduler.codeplex.com/
using (var ts = new TaskService())
{
Task task = ts.GetTask("My task");
task.Run();
}

Printing a PDF in C#

I am making a C# Windows application for printing a PDF.
When I open the application, it only opens the Acrobat Reader window and no more printing. Is there anything I have missed in the function of Print()?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using Microsoft.Win32;
namespace PrintDocumentsApplication
{
public partial class PrintForm : Form
{
public PrintForm()
{
InitializeComponent();
}
private void printPdfButton_Click(object sender, EventArgs e)
{
String File = #"C:\Documents and Settings\larasasasrylo\Desktop\QRCODE_DEMO\test.pdf";
String Printer = "\\vhssadasdasoftaweafs\\HP Color LaserJet 5550 PCL 6";
Print(File, Printer);
}
public static bool Print(string file, string printer)
{
try
{
Process.Start(
Registry.LocalMachine.OpenSubKey(
#"SOFTWARE\Microsoft\Windows\CurrentVersion" +
#"\App Paths\AcroRd32.exe").GetValue("").ToString(),
string.Format("/h /t \"{0}\" \"{1}\"", file, printer));
return true;
}
catch { }
return false;
}
}
}
you try this
Process process = new Process();
process.StartInfo.FileName = pathToPdfOrDocFile;
process.UseShellExecute = true;
process.StartInfo.Verb = "printto";
process.StartInfo.Arguments = "\"" + printerName + "\"";
process.Start();
process.WaitForInputIdle();
process.Kill();

How to execute "del data.txt" using Process?

The following trivial code is just an example that does not reflect my real scenario.
I have tried it and it did not work.
I want to delete data.txt using Process rather than using File class.
using System;
using System.Diagnostics;
namespace Tester
{
class Program
{
static void Main(string[] args)
{
Process p = new Process();
p.StartInfo.FileName = "cmd";
p.StartInfo.Arguments = "del data.txt";
p.StartInfo.UseShellExecute=false;
p.EnableRaisingEvents = true;
p.Exited += (sender, e) => { Console.WriteLine("Finished"); };
p.Start();
p.WaitForExit();
}
}
}
How to execute del data.txt using Process?
You need to add the "/C" argument to the process.
p.StartInfo.Arguments = "/C del data.txt";
Apparently because cmd doesn't handle arguments like that. You have to add /C (and maybe quotes) to the argument:
p.StartInfo.Arguments = "/C \"del data.txt\"";

How to run external program via a C# program?

How do I run an external program like Notepad or Calculator via a C# program?
Maybe it'll help you:
using(System.Diagnostics.Process pProcess = new System.Diagnostics.Process())
{
pProcess.StartInfo.FileName = #"C:\Users\Vitor\ConsoleApplication1.exe";
pProcess.StartInfo.Arguments = "olaa"; //argument
pProcess.StartInfo.UseShellExecute = false;
pProcess.StartInfo.RedirectStandardOutput = true;
pProcess.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
pProcess.StartInfo.CreateNoWindow = true; //not diplay a windows
pProcess.Start();
string output = pProcess.StandardOutput.ReadToEnd(); //The output result
pProcess.WaitForExit();
}
Use System.Diagnostics.Process.Start
Hi this is Sample Console Application to Invoke Notepad.exe ,please check with this.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
namespace Demo_Console
{
class Program
{
static void Main(string[] args)
{
Process ExternalProcess = new Process();
ExternalProcess.StartInfo.FileName = "Notepad.exe";
ExternalProcess.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;
ExternalProcess.Start();
ExternalProcess.WaitForExit();
}
}
}
For example like this :
// run notepad
System.Diagnostics.Process.Start("notepad.exe");
//run calculator
System.Diagnostics.Process.Start("calc.exe");
Follow the links in Mitchs answer.

Categories