0

When I click on the print button, the program saves an image to a certain file name. The program then gets the file and print it. But when I do it a second time, the file is in use by another process, even though the printing is done. Is there any way that I can close the file before the print button is pressed again?

private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
    string pathImage = Environment.CurrentDirectory + "\\chart1.png";
    chart1.SaveImage(pathImage, System.Windows.Forms.DataVisualization.Charting.ChartImageFormat.Png);
    Image newImage = Image.FromFile(pathImage);
    Point ulCorner = new Point(50, 425);
    e.Graphics.DrawImage(newImage, ulCorner);
}

private void button4_Click(object sender, EventArgs e)
{        
    if (printPreviewDialog1.ShowDialog() == DialogResult.OK)
    {
        printDocument1.Print();
    }
}
DonBoitnott
  • 10,787
  • 6
  • 49
  • 68
  • 2
    You need to call `newImage.Dispose()` or use `using (Image newImage ...`. Any time a class isn't doing what you think, [read the docs](https://learn.microsoft.com/en-us/dotnet/api/system.drawing.image.fromfile?view=netframework-4.7.1#System_Drawing_Image_FromFile_System_String_). – Dour High Arch Mar 24 '19 at 22:27
  • There are many Q&A on the site already about this exact problem. Try using the search feature, entering the exact error message you receive and relevant keywords like "image" or "save". See marked duplicate for one such example. – Peter Duniho Mar 24 '19 at 22:32
  • @PeterDuniho Although I'd say of all the dupes you might have chosen, that one is about the worst. Another of Hans's famously spartan answers... – DonBoitnott Mar 25 '19 at 10:51

1 Answers1

1

Probably because you're not releasing the image:

private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
    string pathImage = Environment.CurrentDirectory + "\\chart1.png";
    chart1.SaveImage(pathImage, System.Windows.Forms.DataVisualization.Charting.ChartImageFormat.Png);
    using (var newImage = Image.FromFile(pathImage))
    {
        Point ulCorner = new Point(50, 425);
        e.Graphics.DrawImage(newImage, ulCorner);
    }
}

Remember that Image is IDisposable.

DonBoitnott
  • 10,787
  • 6
  • 49
  • 68