Hey guys,
I'm trying to print files from a directory. Basically, I have a web page that generates reports into PDFs and writes them to a shared directory. I also have a Windows service that monitors that directory. When a file is saved to that directory, it should print the file and then delete it. I'm running into some problems with the timing between the printing and the deleting of the files and I'm wondering if anyone can help. Here's what I have so far:
Code:
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;
using PdfSharp;
using PdfSharp.Pdf.Printing;
using System.Threading;
namespace InvoiceMonitor
{
public partial class InvoiceMonitor : ServiceBase
{
private const string _targetDirectory = @"C:\report\";
private const string _adobeDirectory = @"C:\Program Files\Adobe\Reader 9.0\Reader\AcroRd32.exe";
private const string _printer1Name = "HP LaserJet M4345 MFP PS";
public InvoiceMonitor()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
CreateWatcher();
}
protected override void OnStop()
{
}
public void CreateWatcher()
{
// Create a new FileSystemWatcher.
FileSystemWatcher invoiceWatcher = new FileSystemWatcher();
// Set the filter to only catch PDF files.
invoiceWatcher.Filter = "*.pdf";
// Subscribe to the Created event.
invoiceWatcher.Created += new FileSystemEventHandler(watcher_FileCreated);
// Set the path
invoiceWatcher.Path = _targetDirectory;
// Enable the FileSystemWatcher events.
invoiceWatcher.EnableRaisingEvents = true;
}
public void watcher_FileCreated(object sender, FileSystemEventArgs e)
{
try
{
PrintDocument(_targetDirectory, e.FullPath);
DeleteFile(_targetDirectory, e.FullPath);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private void PrintDocument(string targetDirectory, string fileName)
{
if (Directory.Exists(targetDirectory))
{
FileInfo file = new FileInfo(fileName);
if (file.Exists)
{
PdfFilePrinter.AdobeReaderPath = _adobeDirectory;
PdfFilePrinter printer = new PdfFilePrinter(fileName, _printer1Name);
printer.Print();
}
else
{
// Do some logging.
}
}
else
{
// Do some logging.
}
}
private void DeleteFile(string targetDirectory, string fileName)
{
if (Directory.Exists(targetDirectory))
{
FileInfo file = new FileInfo(fileName);
if (file.Exists)
{
file.Delete();
}
else
{
// Do some logging.
}
}
else
{
// Do some logging
}
}
}
}
I think what happens is that it doesn't have enough time to set up the print job before the file gets removed from the directory. Could anyone provide any advice/guidance on solving my problem? Thanks