我有一个Windows服务,使用FileSystemWatcher监视文件夹,打印添加的图像,然后在打印后删除该图像。
问题在于,当我尝试删除文件时,会抛出异常:
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());
}
}
}
问题在于,当我尝试删除文件时,会抛出异常:
Error: System.IO.IOException: The process cannot access the file because it is being used by another process.
我猜测是因为FileSystemWatcher正在保持对该文件的某种引用。你有什么办法,在文件打印后删除该文件吗?
编辑:
之前没有包含我的代码中的这个函数: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;
}
}
我也将using块建议应用到了这个函数中,并将删除操作移动到了这个函数中,这个函数是mydoc.EndPrint的事件处理程序,以确保与文件的所有联系都被断开,这似乎解决了问题。
void myDoc_EndPrint(object sender, PrintEventArgs e)
{
File.Delete(FilePath);
}
FileMon
查看哪些进程正在锁定该文件。 - Oded