【问题标题】:WPF Application can't delete/save a file [duplicate]WPF应用程序无法删除/保存文件[重复]
【发布时间】:2019-03-11 21:35:00
【问题描述】:

我有一个正在 WPF 中编写的应用程序。这很简单,我有这个字符串类型的属性,它读取图像文件 (.png) 的路径并检查它的分辨率。如果 dpi 不是 96,那么它将分辨率设置为 96。简单。好吧,我完成了那部分,但是,当我必须删除旧文件并将其保存为具有正确分辨率的文件时,我收到一条错误消息:

System.IO.IOException: 'The process cannot access the file 'C:\MyAwesomeProjects\Resources\Button_A.png' because it is being used by another process.'

这就是我在代码中所做的。这是在我的 ViewModel 中

    private string _bkImage = "";
    public virtual string BkImage
    {
        get {return _bkImage ;}
        set{
        FileStream stream = new FileStream(value, FileMode.Open, FileAccess.Read);
        Bitmap bmpFromFile = (Bitmap)System.Drawing.Image.FromFile(stream.Name);

        if(Math.Round(bmpFromFile.HorizontalResolution) != 96 && Math.Round(bmpFromFile.VerticalResolution) != 96)
        {
           bmpFromFile.SetResolution(96, 96);
           File.Delete(stream.Name); //This is where I get the error
           bmpFromFile.Save($"{stream.Name}");
           bmpFromFile.Dispose();
         }                
         control.Image.Source = new BitmapImage(new Uri(stream.Name)); //assigning the new image here

//... more non-related code here
       }
    }

我被这个错误难住了。我在做一些不正常的事情吗?非常感谢。

【问题讨论】:

  • 抱歉,您的代码一团糟。您没有在视图模型属性的设置器中认真设置 Image 元素的 Source 属性吗?为什么要更改位图分辨率,而不是简单地调整 Image 元素的大小?
  • System.IO.IOException: 'The process cannot access the file 'C:\MyAwesomeProjects\Resources\Button_A.png' because it is being used by another process.' 在您的情况下意味着您在当前进程中使用此文件。因此,您需要在尝试删除文件之前关闭/处置所有访问该文件的内容。在你的情况下,我相信它是stream
  • @tukaef 不,它是保持文件打开的 BitmapImage。

标签: c# wpf


【解决方案1】:

根据文档System.Drawing.Image.FromFile 保护它正在使用的文件,直到它被处理掉。这意味着您必须在调用 bmpFromFile.Dispose(); 后使用正确的名称保存文件

我建议先将此文件保存到另一个专门用于保存新图像的临时文件夹中,然后再在程序中处理绘制的图像。将这个新保存的图像的位置存储为字符串,删除原始照片后将其移动到原始文件夹中。

让我知道这是否有意义,我现在正在使用手机,但如果您需要,我可以为您输入代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-04
    • 1970-01-01
    • 2020-02-21
    • 2016-07-30
    • 1970-01-01
    • 2014-09-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多