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()

  • 相关阅读:
    POJ 1401 Factorial
    POJ 2407 Relatives(欧拉函数)
    POJ 1730 Perfect Pth Powers(唯一分解定理)
    POJ 2262 Goldbach's Conjecture(Eratosthenes筛法)
    POJ 2551 Ones
    POJ 1163 The Triangle
    POJ 3356 AGTC
    POJ 2192 Zipper
    POJ 1080 Human Gene Functions
    POJ 1159 Palindrome(最长公共子序列)
  • 原文地址:https://www.cnblogs.com/ZXdeveloper/p/3779755.html
Copyright © 2011-2022 走看看