【发布时间】: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