zoukankan      html  css  js  c++  java
  • 【转】“正由另一进程使用,因此该进程无法访问该文件”的问题&解决方法

    正在写一个手指画图的程序
    C# + WPF
    其中有一部分是加载外部某PNG文件,放入BitmapImage,再作为Image的Source显示在Canvas上
    画了几笔之后,再存回这个PNG文件

    ================问题=================
    BitmapImage这个对象没有Dispose方法,始终无法释放,因此在之后FileStream试图写这个文件时出现“正由另一进程使用,因此该进程无法访问该文件”的问题

    BitmapImage bitmap = new BitmapImage();
    bitmap.BeginInit();
    bitmap.UriSource = new Uri(filePath);
    bitmap.EndInit();
    
    Image currentImage .Source = bitmap;
    canvas.Children.Add(currentImage);
    
    // Do some modification
    
    private void ExportToPng( string path, Canvas surface)
    {
    if(path == null)
    return;
    ........
    using(FileStream outStream = new FileStream(path, FileMode.Create)
    ........
    }

    尝试了很多方法,包括在using FileStream之前加lock、在new FileStream的参数中加入FileAccess.ReadWrite、FileShare.ReadWrite、以及将bitmap.Clone作为currentImage的Source,都不成功


    ===============解决方法=============
    最后发现初始化BitmapImage可以通过byte[]进行,于是只能通过将png文件读成byte[],再进行BitmapImage的初始化,就没有问题了

    // Read byte[] from png file
    BinaryReader binReader = new BinaryReader(File.Open(filePath, FileMode.Open));
    FileInfo fileInfo = new FileInfor(filePath);
    byte[] bytes = binReader.ReadBytes((int)fileInfo.Length);
    binReader.Close();
    
    // Init bitmap
    BitmapImage bitmap = new BitmapImage();
    bitmap.BeginInit();
    bitmap.StreamSource = new MemoryStream(bytes);
    bitmap.EndInit();

    为了更加保险,最后使用的方法中通过ref参数,将需要init的bitmap作为参数传入,方法内部生成一个temp的BitmapImage,完成Init后,bitmap = temp.Clone()

  • 相关阅读:
    3个同一行div的摆放div
    Android 项目开发
    iOS 8
    iOS 8
    __FILE__ 与 $_SERVER['SCRIPT_FILENAME']的区别
    高德百度坐标系转换方法
    高德百度坐标系转换方法
    在iOS开发中使用icon font的方法
    在iOS开发中使用icon font的方法
    UIView的setNeedsLayout, layoutIfNeeded 和 layoutSubviews 方法之间的关系解释
  • 原文地址:https://www.cnblogs.com/ZXdeveloper/p/3779755.html
Copyright © 2011-2022 走看看