【问题标题】:running a batch file from C#从 C# 运行批处理文件
【发布时间】:2011-10-29 09:39:30
【问题描述】:

更新 ** 仍在寻找正确的答案 ** 我的 Windows 服务中有以下代码,我想运行一个批处理文件。我希望打开命令提示符窗口,以便查看进度

这是我的代码,但我的批处理文件代码不起作用

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.IO;

    namespace Watcher
    {
        public partial class Watcher : ServiceBase
        {
            public Watcher()
            {
                InitializeComponent();
            FolderWatcher.Created += FolderWatcher_Created;
            FolderWatcher.Deleted += FolderWatcher_Deleted;
            FolderWatcher.Renamed += FolderWatcher_Renamed;
            }

            protected override void OnStart(string[] args)
            {

                          // Start the child process.
            Process p = new Process();
            // Redirect the output stream of the child process.
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.FileName = "C:\\myFile.bat";
            p.Start();
            // Do not wait for the child process to exit before
            // reading to the end of its redirected stream.
            // p.WaitForExit();
            // Read the output stream first and then wait.
            string output = p.StandardOutput.ReadToEnd();
            p.WaitForExit();


            }

            protected override void OnStop()
            {
            }

            private void FolderWatcher_Created(object sender, System.IO.FileSystemEventArgs e)
            {
                TextWriter writer = new StreamWriter("C:\\folder\\FolderLog.txt", true);
                writer.WriteLine(DateTime.Now + " A new folder/file with name " + e.Name + " has been created. ");
                writer.Close();
            }

            private void FolderWatcher_Deleted(object sender, System.IO.FileSystemEventArgs e)
            {
                TextWriter writer = new StreamWriter("C:\\folder\\FolderLog.txt", true);
                writer.WriteLine(DateTime.Now + " A new folder/file with name " + e.Name + " has been deleted. ");
                writer.Close();
            }

            private void FolderWatcher_Renamed(object sender, System.IO.RenamedEventArgs e)
            {
                TextWriter writer = new StreamWriter("C:\\folder\\log.txt", true);
                writer.WriteLine(DateTime.Now + " A new folder/file with name " + e.Name + " has been renamed. ");
                writer.Close();
            }


        }
    }

它不执行批处理文件。我是 .net 和 C# 的新手,我不知道从这里做什么。 谢谢

【问题讨论】:

  • 您能以任何方式确认服务正在运行吗?
  • 服务运行良好。我可以从命令行启动它。我可以重命名/删除/添加文件夹并记录信息。所以我 100% 确定服务运行良好
  • 附带说明:您应该将StreamWriters 包裹在using 中,否则您可能会留下打开的文件句柄。

标签: c# .net visual-studio-2010 c#-4.0 windows-services


【解决方案1】:

How to run console application from Windows Service?

我相信你会想用 FileName="cmd.exe" 和 Arguments="c:\\thebatfile.bat" 设置 p.StartInfo

【讨论】:

  • @Autolycus 是的,但您需要将参数更改为/C "c:\myFile.bat"(缺少/C)。
【解决方案2】:

问题是您将 UseShellExecute 设置为 false,但您没有传递可执行文件的名称。

ShellExecute被使用时,它类似于在资源管理器中双击一个文件——它知道.doc文件需要用Word打开,而.bat文件需要用cmd.exe打开。但是,当您禁用此功能时,它不知道这些事情,您需要传递一个 executable 才能成功运行任何东西。

当您将 RedirectStandardOutput 设置为 true 时,您需要通过将 FileName 设置为 cmd.exe 并将参数设置为 /C "c:\myFile.bat" 来通过 cmd.exe 运行批处理文件:

p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "/C \"c:\\myFile.bat\"";

【讨论】:

  • 很好的解释!谢谢!
【解决方案3】:

看起来它在服务首次运行时正在运行批处理脚本,然后在其他函数能够被调用之前退出 (p.WaitForExit();)。这是预期的行为吗?这可以解释为什么您可以看到它执行文件夹操作而看不到正在运行的脚本。

试试这个代码来调出控制台窗口。它应该让您了解批处理脚本何时运行。

protected override void OnStart(string[] args)
{
        // Start the child process.
        Process p = new Process();
        // Redirect the output stream of the child process.
        p.StartInfo.UseShellExecute = false;

        /*
        This is commented out so we can see what the script is doing
        inside the cmd console.
        */
        //p.StartInfo.RedirectStandardOutput = true;

        p.StartInfo.FileName = "C:\\myFile.bat";
        p.Start();
        // Do not wait for the child process to exit before
        // reading to the end of its redirected stream.
        // p.WaitForExit();
        // Read the output stream first and then wait.

        /*
        Since we aren't redirecting the output, we have to comment out
        this line or we get an error
        */
        //string output = p.StandardOutput.ReadToEnd();

        p.WaitForExit();
}

【讨论】:

    【解决方案4】:

    我怀疑您的服务或 bat 文件。修改源代码打开记事本!检查记事本是否出现!如果是,那么我们可以进一步调查!

    【讨论】:

    【解决方案5】:

    您的批处理文件在做什么?假设您已确认这运行正常。

    【讨论】:

    【解决方案6】:

    Windows 服务在无桌面用户帐户下运行。要查看 cmd 窗口,您必须模拟当前登录的用户并在该用户的桌面上启动 cmd 窗口。看到这个:

    Windows Impersonation from C#

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-18
      • 2012-08-07
      • 2011-02-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多