从C#调用批处理文件 [英] Calling Batch File From C#

查看:66
本文介绍了从C#调用批处理文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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";
    }
}

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

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)

推荐答案

这应该有效

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

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

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

这篇关于从C#调用批处理文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆