我有一个使用 FileSystemWatcher 的 Windows 服务来监视文件夹、打印添加的图像,然后在打印后删除图像。
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.
that the file is being used by another当我尝试删除它时的过程。我猜这是因为 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 block 建议,但也将删除移动到这个函数,它是 mydoc.EndPrint 的事件处理程序,以确保切断与文件的所有联系,这似乎可以解决问题。
void myDoc_EndPrint(object sender, PrintEventArgs e)
{
File.Delete(FilePath);
}
最佳答案
PrintDocument 实现了 IDisposable,您需要确保它通过将其包装在 using block 中来释放它的文件句柄。
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
{
using (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());
}
}
}
关于c# - 使用 FileSystemWatcher 触发事件,然后删除新创建的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3825302/