I have a small C# ASP.NET web application which generates several PNG image files from dynamically created .NET Chart controls. These are then used to:
- Create a lightbox effect
- Create a PDF
- Create a Zip file
The application gets little usage and the data is updated often, so I'm re-creating everything on each load. The problem is, the files are often "in use" and throw an exception when I try to overwrite. I can't have the exception because the correct new versions of the charts need to be displayed, not the old ones. I've thought of deleting first, but still there are problems. Because the page needs to "just work" each time, I've resorted to manually deleting the image files after every data refresh, but this seems ridiculous. I have something like this:
if(!System.IO.File.Exists(Server.MapPath(ImageFilename))) {
chart.SaveImage(Server.MapPath(imageFilename), ChartImageFormat.Png);
}
And for the PDF, something like this which I know is gross:
try
{
Document doc = new Document();
System.IO.File.Delete(Server.MapPath("charts.pdf"));
PdfWriter.GetInstance(doc, new FileStream(Server.MapPath("charts.pdf"), FileMode.Create));
doc.Open();
///ADD DATA
doc.Close();
}
catch(Exception exc)
{}
How can I get around the file issues and force an overwrite instead of manual or automatic delete with a swallowed exception? I can always delete just fine in Explorer. Or alternatively, am I thinking about this the wrong way and should try a different tack?