Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Batch File From C#

Tags:

c#

cmd

I am hoping that this is an easy question, but i have the following code in my C# application and for some reason it will not execute the batch file I am pointing to.

private void filesystemwatcher_Renamed(object sender, System.IO.RenamedEventArgs e)
{
    if (File.Exists("C:\\Watcher\\File.txt"))
    {
        System.Diagnostics.Process proc = new System.Diagnostics.Process();
        proc.EnableRaisingEvents = false;
        proc.StartInfo.FileName = "C:\\Watcher\\Cleanup.bat";
        proc.Start();
        MessageBox.Show("Cleaned up files, your welcome.");

    }
    else
    {
        label4.Text = "Error: No file found";
    }
}

It will display the messagebox correctly so I know that it is reaching that area of code, but I do not see a cmd box pop up or anything that would show that it just ran the batch file. I can also tell because cleanup.bat just renames a file and that's it. After I get the messagebox the file name hasn't changed.

If I double click the batch file manually it works just fine. I have also adjusted the permissions of the batch file to Full Control for everyone (just for testing purposes)

like image 510
Bit10Bytes Avatar asked May 29 '13 20:05

Bit10Bytes


People also ask

What is batch file in C?

It consists of a series of commands to be executed by the command-line interpreter, stored in a plain text file. A batch file may contain any command the interpreter accepts interactively and use constructs that enable conditional branching and looping within the batch file, such as IF , FOR , and GOTO labels.

How do I run a batch file from a website?

Just create a batch file and save in the location where your html file is there. this anchor tag will execute the (test. bat) batch file. After clicking on the link <TEST>, you will get the window prompting to open/save/close, if you will click on open then batch file will be executed.


1 Answers

This should work

System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.FileName = "C:\\Watcher\\Cleanup.bat";
proc.StartInfo.WorkingDirectory = "C:\\Watcher";
proc.Start();

You need to set the WorkingDirectory otherwise the command will be executed in what is the current directory of the calling application

like image 55
Steve Avatar answered Oct 29 '22 22:10

Steve