从C#调用批处理文件
我希望这是一个简单的问题,但我在我的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"; } }
它将正确显示消息框,因此我知道它已到达该代码区域,但我没有看到弹出的cmd框或任何显示它只是运行批处理文件的内容。 我也可以告诉因为cleanup.bat只是重命名一个文件,就是这样。 收到消息框后,文件名未更改。
如果我手动双击批处理文件,它可以正常工作。 我还将批处理文件的权限调整为每个人的完全控制(仅用于测试目的)
这应该工作
System.Diagnostics.Process proc = new System.Diagnostics.Process(); proc.StartInfo.FileName = "C:\\Watcher\\Cleanup.bat"; proc.StartInfo.WorkingDirectory = "C:\\Watcher"; proc.Start();
您需要设置WorkingDirectory,否则命令将在调用应用程序的当前目录中执行
尝试将proc.StartInfo.UseShellExecute
设置为true
; 这告诉操作系统执行文件扩展名查找以在注册表中找到正确的处理程序。