Search code examples
c#winformsoffice-interopmschart

PieChart.SaveImage(path,imageFormate) show exception on saving image 2nd time


I am using Chart Control of .NET 4.0 framework in Windows Forms Application i have been saving Pie Chart image on location through PieChart.SaveImage(Path,ChartImageFormat.Png), when i create doc file with Microsoft.Office.Interop.Word i paste that image in that document. it proceed first time very well and .doc created successfully, but i try to save pie chart 2nd time during win forms Running it give an System.IO.Exception

"The process cannot access the file 'path' because it is being used by another process."

When i terminate program and run it again it over wright previous image but when i want to save image 2nd time during program running it gives same Exception

This is how i am saving image

private Void SavePieChart()
{
    string PieChartPath= Application.StartupPath + @"\Chart.png";
    PieChart.SaveImage(PieChartPath, ChartImageFormat.Png);
}

I searched, but did not find any efficient solution which solve my problem, If anything doing wrong Kindly Point out my mistake, or any helping link to solve this. .

EDIT 1

This is where I am pasting that image in Doc file

System.Drawing.Image PieChart =System.Drawing.Image.FromFile(PieChartPath);
oHeader1 = oDoc.Content.Paragraphs.Add(ref oMissing);
Logothread = new Thread(() => Clipboard.SetImage(PieChart));
Logothread.SetApartmentState(ApartmentState.STA); //Set the thread to STA
Logothread.Start();
Logothread.Join();
oHeader1.Range.Paste();
oHeader1.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
oHeader1.Range.InsertParagraphAfter();

Thanks in advance


Solution

  • Problem is when i wast pasting image in doc file i was take image like

    System.Drawing.Image PieChart =System.Drawing.Image.FromFile(PieChartPath);
    

    as Reza and Taw described FromFile() keeps the file in use so that's why when i try to save image 2nd time it shows exception the file is already in process,

    The i use FromStram() add this into my code

    byte[] DataBytes= System.IO.File.ReadAllBytes(PieChartPath);
    System.IO.MemoryStream ms = new System.IO.MemoryStream(DataBytes);
    
    System.Drawing.Image PieChart = System.Drawing.Image.FromStream(ms);