Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

running a batch file from C#

UPDATE ** STILL LOOKING FOR A CORRECT ANSWER ** I have the following code in my windows service and I want to run a batch file. I want the command prompt window up so I can see progress

here is my code but my batch file code doesnt work

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.IO;

    namespace Watcher
    {
        public partial class Watcher : ServiceBase
        {
            public Watcher()
            {
                InitializeComponent();
            FolderWatcher.Created += FolderWatcher_Created;
            FolderWatcher.Deleted += FolderWatcher_Deleted;
            FolderWatcher.Renamed += FolderWatcher_Renamed;
            }

            protected override void OnStart(string[] args)
            {

                          // Start the child process.
            Process p = new Process();
            // Redirect the output stream of the child process.
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.FileName = "C:\\myFile.bat";
            p.Start();
            // Do not wait for the child process to exit before
            // reading to the end of its redirected stream.
            // p.WaitForExit();
            // Read the output stream first and then wait.
            string output = p.StandardOutput.ReadToEnd();
            p.WaitForExit();


            }

            protected override void OnStop()
            {
            }

            private void FolderWatcher_Created(object sender, System.IO.FileSystemEventArgs e)
            {
                TextWriter writer = new StreamWriter("C:\\folder\\FolderLog.txt", true);
                writer.WriteLine(DateTime.Now + " A new folder/file with name " + e.Name + " has been created. ");
                writer.Close();
            }

            private void FolderWatcher_Deleted(object sender, System.IO.FileSystemEventArgs e)
            {
                TextWriter writer = new StreamWriter("C:\\folder\\FolderLog.txt", true);
                writer.WriteLine(DateTime.Now + " A new folder/file with name " + e.Name + " has been deleted. ");
                writer.Close();
            }

            private void FolderWatcher_Renamed(object sender, System.IO.RenamedEventArgs e)
            {
                TextWriter writer = new StreamWriter("C:\\folder\\log.txt", true);
                writer.WriteLine(DateTime.Now + " A new folder/file with name " + e.Name + " has been renamed. ");
                writer.Close();
            }


        }
    }

It does not execute the batch file. I am a newbie in .net and C# and I am not sure what to do from here. thanks

like image 484
Asim Zaidi Avatar asked Aug 18 '11 01:08

Asim Zaidi


People also ask

How do I run a batch file from an argument in C#?

string MyBatchFile = @"C:\Program Files (x86)\MybatchFile. bat"; string _sourcePath = @"C:\FolderToCopy"; string _tempTargetPath = @"C:\TargetFolder\"; var process = new Process { StartInfo = { Arguments = string. Format("{0} {1}", _sourcePath, _tempTargetPath) } }; process.

How do I run a .cmd file in command prompt?

Type "start [filename.exe]" into Command Prompt, replacing "filename" with the name of your selected file. Replace "[filename.exe]" with your program's name. This allows you to run your program from the file path.

What is %% A in CMD?

Use double percent signs ( %% ) to carry out the for command within a batch file. Variables are case sensitive, and they must be represented with an alphabetical value such as %a, %b, or %c. ( <set> ) Required. Specifies one or more files, directories, or text strings, or a range of values on which to run the command.


2 Answers

How to run console application from Windows Service?

You will want to the set the p.StartInfo with FileName="cmd.exe" and Arguments="c:\\thebatfile.bat" i believe

like image 78
Mike Zboray Avatar answered Oct 13 '22 00:10

Mike Zboray


The problem is that you have UseShellExecute as false, but you aren't passing the name of an executable.

When ShellExecute is being used its similar to double clicking on a file in explorer - it knows that .doc files need to be opened with Word, and that .bat files need to be opened with cmd.exe. When you have this disabled however it knows none of these things and you need to pass an executable in order for anything to be run successfully.

As you are setting RedirectStandardOutput to true you need to instead run the batch file via cmd.exe by setting FileName to cmd.exe and the arguments to /C "c:\myFile.bat":

p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "/C \"c:\\myFile.bat\"";
like image 38
Justin Avatar answered Oct 12 '22 22:10

Justin