简体   繁体   English

从C#运行批处理文件

[英]running a batch file from C#

UPDATE ** STILL LOOKING FOR A CORRECT ANSWER ** I have the following code in my windows service and I want to run a batch file. 更新 **仍然正在寻找一个正确的答案**我的Windows服务中有以下代码,我想运行一个批处理文件。 I want the command prompt window up so I can see progress 我想要命令提示窗口,以便我可以看到进度

here is my code but my batch file code doesnt work 这是我的代码,但我的批处理文件代码不起作用

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();
            }


        }
    }

It does not execute the batch file. 它不执行批处理文件。 I am a newbie in .net and C# and I am not sure what to do from here. 我是.net和C#的新手,我不知道该怎么做。 thanks 谢谢

How to run console application from Windows Service? 如何从Windows服务运行控制台应用程序?

You will want to the set the p.StartInfo with FileName="cmd.exe" and Arguments="c:\\\\thebatfile.bat" i believe 您将要设置p.StartInfo与FileName =“cmd.exe”和Arguments =“c:\\\\ thebatfile.bat”我相信

The problem is that you have UseShellExecute as false, but you aren't passing the name of an executable. 问题是您将UseShellExecute为false,但您没有传递可执行文件的名称。

When ShellExecute is being used its similar to double clicking on a file in explorer - it knows that .doc files need to be opened with Word, and that .bat files need to be opened with cmd.exe . 当使用ShellExecute ,它类似于双击资源管理器中的文件 - 它知道需要使用Word打开.doc文件,并且需要使用cmd.exe打开.bat文件。 When you have this disabled however it knows none of these things and you need to pass an executable in order for anything to be run successfully. 如果您已禁用此功能但它不知道这些内容,您需要传递可执行文件才能成功运行任何内容。

As you are setting RedirectStandardOutput to true you need to instead run the batch file via cmd.exe by setting FileName to cmd.exe and the arguments to /C "c:\\myFile.bat" : 当您将RedirectStandardOutput设置为true时,您需要通过将FileName设置为cmd.exe并将参数设置为/C "c:\\myFile.bat"来通过cmd.exe运行批处理文件:

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

Windows services run under a desktopless user account. Windows服务在无桌面用户帐户下运行。 To see the cmd window you must impersonate the current logged user and start the cmd window on this user's desktop. 要查看cmd窗口,您必须模拟当前登录的用户并在此用户的桌面上启动cmd窗口。 See this: 看到这个:

Windows Impersonation from C# 来自C#的Windows模拟

It looks like it's running the batch script when the service is first run and then it quits ( p.WaitForExit(); ) before the other functions get the ability to be called. 看起来它在首次运行服务时运行批处理脚本然后退出( p.WaitForExit(); ),然后其他函数才能被调用。 Is that the intended behavior? 这是预期的行为吗? That would explain why you can see it do the folder operations and not see the script being run. 这可以解释为什么你可以看到它执行文件夹操作而不是看到正在运行的脚本。

Try this code to bring up the console window. 尝试使用此代码调出控制台窗口。 It should give you an idea of when the batch script is running. 它应该让您了解批处理脚本何时运行。

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();
}

i am doubting your service or the bat file. 我怀疑你的服务或蝙蝠文件。 modify the source code to open a notepad! 修改源代码打开记事本! check if notepad shows up!! 检查记事本是否显示!! if yes then we can investigate further! 如果是,那么我们可以进一步调查!

What is your batch file doing? 你的批处理文件在做什么? Assume you've confirmed that this IS running OK. 假设您已确认此IS正常运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM