【发布时间】:2010-09-29 19:49:28
【问题描述】:
我有一个 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查看哪些进程正在锁定文件。
标签: c# windows-services filesystemwatcher