I am using the following code to create a file at a temp path and then delete it after the print happened successfully. But after printing I try to dispose the file and when I try to delete the file, I still get an exception saying "The process cannot access the file 'Chart0.png' because it is being used by another process." Please help.
I also tried putting the deleting code in the finally block but still no luck.
public static bool PrintAllCharts(Dictionary<string, ILightningChartInterface> charts)
{
DirectoryInfo info = null;
try
{
string FilePathWithoutFileName = string.Empty;
info = Directory.CreateDirectory(@"C:\TempCharts");
for (int i = 0; i < charts.Count; i++)
{
KeyValuePair<string, ILightningChartInterface> kp = charts.ElementAt(i);
FilePathWithoutFileName = info.FullName;
string FullPath = string.Format("{0}/Chart{1}.png", FilePathWithoutFileName, i.ToString());
kp.Value.SaveChartToFile(FullPath);
}
var files = Directory.GetFiles(FilePathWithoutFileName);
using (var pdoc = new PrintDocument())
{
using (var pdi = new System.Windows.Forms.PrintDialog { Document = pdoc, UseEXDialog = true })
{
if (pdi.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
pdoc.PrinterSettings = pdi.PrinterSettings;
pdoc.PrintPage += Pdoc_PrintPage;
foreach (var file in files)
{
pdoc.DocumentName = file;
pdoc.Print();
}
}
}
}
//Dispose the file after printing.
foreach(var file in files)
{
Image.FromFile(file).Dispose();
File.Delete(file); //This line gives an exception
}
foreach (DirectoryInfo dir in info.GetDirectories())
{
dir.Delete(true);
}
return true;
}
catch (Exception ex)
{
return false;
}
}
private static void Pdoc_PrintPage(object sender, PrintPageEventArgs e)
{
string file = ((PrintDocument)sender).DocumentName;
System.Drawing.Image img = System.Drawing.Image.FromFile(file);
Rectangle m = e.MarginBounds;
if ((double)img.Width / (double)img.Height > (double)m.Width / (double)m.Height) // image is wider
{
m.Height = (int)((double)img.Height / (double)img.Width * (double)m.Width);
}
else
{
m.Width = (int)((double)img.Width / (double)img.Height * (double)m.Height);
}
e.Graphics.DrawImage(img, m);
}