I have a windows service using a FileSystemWatcher to monitor a folder, print added images, then delete the image after printing.
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
FileSystemWatcher Watcher = new FileSystemWatcher();
Watcher.Path = @"C:\Images";
Watcher.Created += new FileSystemEventHandler(Watcher_Changed);
Watcher.EnableRaisingEvents = true;
}
private void Watcher_Changed(object sender, FileSystemEventArgs e)
{
try
{
PrintDocument myDoc = new PrintDocument();
myDoc.PrintPage += new PrintPageEventHandler(print);
FilePath = e.FullPath;
myDoc.PrinterSettings.PrinterName = @"\\Network Printer";
myDoc.Print();
using (StreamWriter sw = new StreamWriter("C:\\error.txt"))
{
sw.WriteLine("Printed File: " + FilePath);
}
File.Delete(e.FullPath);
}
catch(Exception excep)
{
using (StreamWriter sw = new StreamWriter("C:\\error.txt"))
{
sw.WriteLine("Error: " + excep.ToString());
}
}
}
The problem is that I get the exception thrown Error: System.IO.IOException: The process cannot access the file because it is being used by another process.
that the file is being used by another process when I try to delete it. I'm guessing this is because the FileSystemWatcher is keeping some sort of reference to it. Any idea on what to do here, to delete the file after it gets printed?
Edit: Did not include this function from my code before:
private void print(object sender, PrintPageEventArgs e)
{
try
{
using (Image i = Image.FromFile(FilePath))
{
Point p = new Point(0, 0);
e.Graphics.DrawImage(i, p);
}
}
catch(Exception exep)
{
throw exep;
}
}
I applied the using block suggestion to this function too, but also moved the delete to this function which is event handler for mydoc.EndPrint, to ensure all ties to the file were cut, and this seems to do the trick.
void myDoc_EndPrint(object sender, PrintEventArgs e)
{
File.Delete(FilePath);
}