【发布时间】:2021-11-16 04:35:34
【问题描述】:
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
try
{
Print();
}
catch (Exception ex)
{
File.AppendAllText(@"C:\fold1\Log.txt", ex.ToString());
}
}
public static void Print()
{
//Print & Move the files after printing
DirectoryInfo sourceinfo = new DirectoryInfo(@"C:\fold");
DirectoryInfo target = new DirectoryInfo(@"C:\fold1");
foreach (FileInfo fi in sourceinfo.GetFiles())
{
if (fi.Length != 0)
{
System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo.CreateNoWindow = true;
process.StartInfo.Verb = "print";
process.StartInfo.FileName = fi.FullName;
process.StartInfo.UseShellExecute = true;
process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
process.Start();
if (!process.WaitForExit(10000))
process.Kill();
}
MoveFile(fi.FullName);
}
}
public static void MoveFile(string Filename)
{
string SourcePath = @"C:\fold";
string targetpath = @"C:\fold1";
if (!Directory.Exists(targetpath))
{
Directory.CreateDirectory(targetpath);
}
string[] sourceFiles = Directory.GetFiles(SourcePath);
foreach (string sourcefile in sourceFiles)
{
string mfilename = Path.GetFullPath(sourcefile);
string mname = Path.GetFileName(sourcefile);
if (mfilename == Filename)
{
string distnition = Path.Combine(targetpath, mname);
File.Move(mfilename, distnition);
}
}
}
protected override void OnStop()
{ try
{
//Move the files after printing
DirectoryInfo sourceinfo = new DirectoryInfo(@"C:\fold");
DirectoryInfo target = new DirectoryInfo(@"C:\fold1");
foreach (FileInfo fi in sourceinfo.GetFiles())
{
// File.AppendAllText(@"C:\fold1\stop.txt", "Stop method");
MoveFile(fi.FullName);
}
}
catch (Exception ex)
{
File.AppendAllText(@"C:\fold1\Log.txt", ex.ToString());
}
}
我创建了一个服务,它在给定目录中静默打印文件,然后将它们移动到另一个目录,当我第一次尝试启动它时它运行良好,但它不会持续运行,我希望它打印和移动任何复制到该目录的文件,那我该怎么办? 请注意,我还是 c# 的初学者,如果你的解释太复杂,我不太明白,谢谢
【问题讨论】:
-
这能回答你的问题吗? Windows service stops automatically
-
上面链接到的文章专门解决了 OnStart 中的 try/catch,但您也应该在其他方法中使用它。任何数量的错误都可能导致服务停止/崩溃。您可能还想使用 NLog、Serilog 或 Log4NET 等日志记录框架添加一些日志记录,以便了解退出时实际发生的情况。
-
不,它不能回答我的问题
标签: c# windows service printing silent