【问题标题】:How to load an image (into an image control) from the file system, then delete it from the file system [duplicate]如何从文件系统加载图像(到图像控件中),然后从文件系统中删除它[重复]
【发布时间】:2014-01-22 04:41:56
【问题描述】:

我遇到了这个非常奇怪的问题,想看看你们是否可以在这里给我一些建议。我想从特定文件 URI 将图像加载到图像控件中,但我也希望可以选择从文件系统中删除文件。问题是我不断收到此错误:

“该进程无法访问文件 'c:\38.gif',因为它正被另一个进程使用。”

这是我的代码(VB.NET 但 C# 解决方案也会有帮助!):

'加载图片

Dim bitmap1 as New BitmapImage
bitmap1.BeginInit()
bitmap1.UriSource = New Uri("c:\38.gif", UriKind.Absolute)
bitmap1.EndInit()
Image1.Source = bitmap1.Clone

然后,如果用户单击一个按钮,我想像这样删除该特定文件:

Image1.Source = Nothing
File.Delete("c:\38.gif")

任何人都知道如何加载图像但仍然能够删除源文件??

提前非常感谢!

【问题讨论】:

  • @TrevorSullivan 该解决方案适用于 WM6,而不是 WPF。我会再看看它,以防万一它引发任何想法。谢谢;)

标签: wpf


【解决方案1】:

只需添加

bitmap1.CacheOption = BitmapCacheOption.OnLoad;

BeginInit() 之后

【讨论】:

  • 我之前试过这个,但它不允许我访问 GIF 动画。我应该在我的问题中包含这个要求,抱歉!
【解决方案2】:

Trevor Sullivan 在他的评论中包含的链接让我找到了答案。以下是处理类似问题的任何人的代码。

    bitmap1 = New BitmapImage

    Using photoStream As System.IO.FileStream = New System.IO.FileStream(currentfile, FileMode.Open, FileAccess.Read)
        bitmap1.BeginInit()
        Using reader As New BinaryReader(photoStream)
            'copy the content of the file into a memory stream
            Dim memoryStream = New MemoryStream(reader.ReadBytes(CInt(photoStream.Length)))
            'make a new Bitmap object the owner of the MemoryStream
            bitmap1.StreamSource = memoryStream
        End Using
        bitmap1.EndInit()
        leimage.Source = bitmap1
        photoStream.Dispose()

    End Using

【讨论】:

    猜你喜欢
    • 2018-12-24
    • 2014-07-04
    • 1970-01-01
    • 2014-09-25
    • 2020-11-24
    • 1970-01-01
    • 2020-03-16
    • 2018-07-22
    • 1970-01-01
    相关资源
    最近更新 更多