Calling Batch File From C#

2019-04-21 00:39发布

问题:

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)

回答1:

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



回答2:

Try setting the proc.StartInfo.UseShellExecute to true; this tells the OS to perform a lookup of the file extension to find the correct handler in the registry.



标签: c# cmd