从 C# 调用批处理文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16823518/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 07:52:58  来源:igfitidea点击:

Calling Batch File From C#

c#cmd

提问by Bit10Bytes

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.

我希望这是一个简单的问题,但我的 C# 应用程序中有以下代码,由于某种原因它不会执行我指向的批处理文件。

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.

它将正确显示消息框,因此我知道它正在到达该代码区域,但我没有看到 cmd 框弹出或任何表明它只是运行批处理文件的内容。我还可以说是因为 cleanup.bat 只是重命名了一个文件,仅此而已。在我收到消息框后,文件名没有改变。

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)

如果我手动双击批处理文件,它工作得很好。我也将批处理文件的权限调整为所有人的完全控制(仅用于测试目的)

采纳答案by Steve

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

您需要设置 WorkingDirectory 否则命令将在调用应用程序的当前目录中执行

回答by wgraham

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

尝试设置proc.StartInfo.UseShellExecutetrue; 这告诉操作系统执行文件扩展名的查找以在注册表中找到正确的处理程序。