调试一个非常简单的代码:Cannot delete background image file in a Chart

Debug a very simple code: Cannot delete background image file in a Chart

表单有一个图表和两个按钮。 Button1是设置Chart1的背景图片为“1.jpg”。按钮 2 正在尝试删除“1.jpg”。点击B1后点击B2出现错误,提示图片文件被其他进程占用,无法删除。

对这里发生的事情有什么想法吗?

'System.IO.IOException' occurred in mscorlib.dll

Additional information: The process cannot access the file 'C:\Projects\Programs\WindowsApplication2\bin\Release.jpg' because it is being used by another process.

这是按钮的 vb.net 代码。

Imports System.IO
Public Class Form1

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Chart1.ChartAreas(0).BackImage = "1.jpg"
End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Chart1.ChartAreas(0).Dispose()
    Chart1.ChartAreas.Clear()

    Try
        File.Delete("1.jpg")
    Catch ex As Exception
        MsgBox(ex.ToString)
    End Try
End Sub

结束Class

我想我明白了。 Chart 对象有一个名为 Images 的 属性。它包含 NamedImage 个对象的集合。您应该做的是为要添加的图像创建一个 NamedImage,然后在进行更改时释放它。请参阅 SetChartImage 方法。

Imports System.Windows.Forms.DataVisualization.Charting
Imports System.IO

Public Class Form1

    Private path1 As String = "C:\Users\Developer\Pictures\tmp.jpg"
    Private path2 As String = "C:\Users\Developer\Pictures\tmp.PNG"

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        SetChartImage(Chart1.ChartAreas(0), path1)
    End Sub

    Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
        SetChartImage(Chart1.ChartAreas(0), path2)
    End Sub

    Private Sub SetChartImage(area As ChartArea, imgpath As String)
        'Create the name
        Dim name As String = Path.GetFileName(imgpath)

        'Clear the backimage property
        area.BackImage = ""

        'Release any current images
        For Each ni As NamedImage In Chart1.Images
            ni.Dispose()
        Next
        Chart1.Images.Clear()

       '****DELETE OLD IMAGE HERE****

        'Create the new Image from file, or in any other way that is
        ' needed.
        Chart1.Images.Add( _
            New NamedImage(name, Image.FromFile(imgpath)) _
        )

        'Update the property
        area.BackImage = name
    End Sub
End Class

BackImage 属性 不仅可以获取图像的完全限定路径,还可以获取 Chart.Images 集合中的 Image 的键名。在 Chart1.Images.Clear() 行之后,您应该可以自由删除之前的图像。