Windows文件监视服务在Server 2008上崩溃

本文关键字:2008 崩溃 Server 文件 监视 服务 Windows | 更新日期: 2023-09-27 18:02:21

我做了一个filewatcher服务,读取放在目录中的每个XML文件,并打印标签上的内容(Visual Studio 2012,Report viewer 2010)。服务在Windows 8上工作正常,但在server 2008 R2上,每次我在目录中复制文件时都会崩溃。

public partial class MyService : ServiceBase
{
    public MyService ()
    {
        InitializeComponent();
        GetSourcePath();
    }
    private void GetSourcePath()
    {
        RegistryKey myKey = Registry.LocalMachine.OpenSubKey("SOFTWARE''Company''MyService", false);
        if (myKey == null)
        {
            fsw.Path = @"C:'Source'";
        }
        else
        {
            fsw.Path = (string)myKey.GetValue("SourcePath");
        }
    }
    protected override void OnStart(string[] args)
    {
        base.OnStart(args);
        fsw.EnableRaisingEvents = true;
    }
    protected override void OnPause()
    {
        base.OnPause();
        fsw.EnableRaisingEvents = false;
    }

    protected override void OnContinue()
    {
        base.OnContinue();
        GetSourcePath();
        fsw.EnableRaisingEvents = true;
    }
    private void fsw_Created(object sender, FileSystemEventArgs e)
    {
        System.Threading.Thread.Sleep(2000);
        ReportViewer reportViewer = new ReportViewer();
        reportViewer.ProcessingMode = ProcessingMode.Local;
        reportViewer.LocalReport.ReportPath = @"rptLabel.rdlc";
        reportViewer.LocalReport.DataSources.Add(new ReportDataSource("DataSet", PrintLabel.GetPrintLabels(e.FullPath)));
        reportViewer.RefreshReport();
        AutoPrint.Export(reportViewer.LocalReport);
        AutoPrint.Print();
    }
    protected override void OnStop()
    {
        fsw.EnableRaisingEvents = false;
    }
}
这里是另一个类 的代码
 public class AutoPrint
{
    private static int m_currentPageIndex;
    private static IList<Stream> m_streams;
    public static Stream CreateStream(string name, string fileNameExtension, Encoding encoding, string mimeType, bool willSeek)
    {
        Stream stream = new MemoryStream();
        m_streams.Add(stream);
        return stream;
    }

    public static void Export(LocalReport report)
    {
        string deviceInfo =
          @"<DeviceInfo>
            <OutputFormat>EMF</OutputFormat>
            <PageWidth>10cm</PageWidth>
            <PageHeight>4cm</PageHeight>
            <MarginTop>0</MarginTop>
            <MarginLeft>0</MarginLeft>
            <MarginRight>0</MarginRight>
            <MarginBottom>0</MarginBottom>
        </DeviceInfo>";
        Warning[] warnings;
        m_streams = new List<Stream>();
        try
        {
            report.Render("Image", deviceInfo, CreateStream, out warnings);
        }
        catch (Exception exc)
        {
            System.Diagnostics.EventLog.WriteEntry("My Service", DateTime.Now.ToLongTimeString() + " Error rendering print : " + exc.Message);
            foreach (Stream stream in m_streams)
            {
                stream.Position = 0;
            }
        }
    }
    public static void Print()
    {
        PrintDocument printDoc = new PrintDocument();
        if(printDoc.PrinterSettings.IsDefaultPrinter) printDoc.PrinterSettings.PrinterName = "Printer Name";
        if (m_streams == null || m_streams.Count == 0) System.Diagnostics.EventLog.WriteEntry("MyService", DateTime.Now.ToLongTimeString() + " Error: no stream to print.");
        if (!printDoc.PrinterSettings.IsValid)
        {
            System.Diagnostics.EventLog.WriteEntry("MyService", DateTime.Now.ToLongTimeString() + " Error: cannot find the default printer.");
        }
        else
        {
            printDoc.PrintPage += new PrintPageEventHandler(PrintPage);
            m_currentPageIndex = 0;
            printDoc.Print();
        }
    }
    public static void PrintPage(object sender, PrintPageEventArgs ev)
    {
        try
        {
            Metafile pageImage = new Metafile(m_streams[m_currentPageIndex]);
            // Adjust rectangular area with printer margins.
            Rectangle adjustedRect = new Rectangle(
                ev.PageBounds.Left - (int)ev.PageSettings.HardMarginX,
                ev.PageBounds.Top - (int)ev.PageSettings.HardMarginY,
                ev.PageBounds.Width,
                ev.PageBounds.Height);
            // Draw a white background for the report
            ev.Graphics.FillRectangle(Brushes.White, adjustedRect);
            // Draw the report content
            ev.Graphics.DrawImage(pageImage, adjustedRect);
            // Prepare for the next page. Make sure we haven't hit the end.
            m_currentPageIndex++;
            ev.HasMorePages = (m_currentPageIndex < m_streams.Count);
        }
        catch (Exception exc)
        {
            System.Diagnostics.EventLog.WriteEntry("MyService", DateTime.Now.ToLongTimeString() + " Error rendering print page: " + exc.Message + "Inner exception :" + exc.InnerException );
        }
    }
}

还有一个用于数据的静态类printLabel,但在本例中没有什么有趣的。它只加载数据。下面是来自日志Event

的第一条错误消息

应用程序:MyService.exe框架版本:v4.0.30319描述:由于未处理的异常,进程被终止。异常信息:System.IO.FileNotFoundException栈:MyService.MyService.fsw_Created(系统。对象,System.IO.FileSystemEventArgs)System.IO.FileSystemWatcher.OnCreated (System.IO.FileSystemEventArgs)在System.IO.FileSystemWatcher。system . string) NotifyFileSystemEventArgs (Int32,在System.IO.FileSystemWatcher。CompletionStatusChanged(UInt32, UInt32, System.Threading.NativeOverlapped*)在System.Threading._IOCompletionCallback。PerformIOCompletionCallback(UInt32, UInt32, System.Threading.NativeOverlapped*)

这里是来自事件日志的第二条消息

故障应用程序名称:MyService.exe,版本:1.0.0.0,时间戳:0x51349c1b故障模块名称:KERNELBASE.dll,版本:6.1.7601.17932,时间戳:0x50327672异常代码:0xe0434352故障偏移量:0x0000c41f故障进程id: 0x2dc4故障应用启动时间:0x01ce18d947393653应用程序路径:C:'Program Files (x86)'Company'MyService' MyService.exe故障模块路径:C:'Windows'syswow64'KERNELBASE.dll报告编号:a27c24e2-84cc-11e2-bb34-0019992623e2

我做了一个与控制台相同的应用程序,它工作得很好。也许服务没有读取文件的权利?

Windows文件监视服务在Server 2008上崩溃

您正在使用相对路径获取FileNotFoundException。这意味着最有可能的问题是您有错误的工作目录。请尝试使用绝对路径。

有关更多信息,请参见Windows服务在哪个目录下运行?

我找到问题了。这是2010年的reportviewer。在安装ReportViewer Service Pack 1之后,它似乎不再崩溃了。崩溃发生在以下行:

ReportViewer reportViewer = new ReportViewer(); 

我也改变了这一行:

reportViewer.LocalReport.ReportEmbeddedResource = "MyService.rptLabel.rdlc";