我想用MemoryStream替换FileStream

时间:2013-01-08 04:16:13

标签: c# .net wpf image dispatcher

我有添加Image的问题,我可以添加一次,如果我添加两个或更多添加它错误:

  

该进程无法访问文件'C:\ Users \ Administrator \ AppData \ Roaming \ afinos \ CaptureImage \ CapImage.Jpg',因为它正由另一个进程使用。我使用以下内容:

 public static void SaveImageCapture(string imgPath, BitmapSource bitmap)
 {
      JpegBitmapEncoder encoder = new JpegBitmapEncoder();
      encoder.Frames.Add(BitmapFrame.Create(bitmap));
      encoder.QualityLevel = 100;

      using (FileStream fstream = new FileStream(imgPath, FileMode.Create))
      {
           encoder.Save(fstream);
           fstream.Close();
           fstream.Dispose();
      }
  }

//Call to use SaveImageCpture

private void btnCapture_Click(object sender, RoutedEventArgs e)
{           
     Dispatcher.Invoke(new Action(delegate()
     {
          string path = "afinos\\" + "CaptureImage\\" + "CapImage.Jpg";

          if (Directory.Exists(path) == false)
          {
               Directory.CreateDirectory(path);   
          }

          Capture_Helper.SaveImageCapture(pathapp + "\\" + path, (BitmapSource)PicCapture.Source);
          ChangeAvatar_vcard.Source = PicCapture.Source;
          txtPath.Text = pathapp + "\\" + path;                   
    }));
}

2 个答案:

答案 0 :(得分:0)

您可以添加标志以停止对同一文件的并行写入。

private bool isCaptureInProgress = false;
private void btnCapture_Click(object sender, RoutedEventArgs e)
{
    if (isCaptureInProgress)
    {
       MessageBox.Show("Capture is already in progress. Please wait to finish it first");
      return;
     }

    Dispatcher.Invoke(new Action(delegate()
        {
            isCaptureInProgress = true;
            string path = "afinos\\" + "CaptureImage\\" + "CapImage.Jpg";
            if (Directory.Exists(path) == false)
            {
                Directory.CreateDirectory(path);   
            }

            Capture_Helper.SaveImageCapture(pathapp + "\\" + path, (BitmapSource)PicCapture.Source);
            ChangeAvatar_vcard.Source = PicCapture.Source;
            txtPath.Text = pathapp + "\\" + path;
           isCaptureInProgress = false;
        }));

}

您需要处理错误处理并确保设置重置标志(最好在finally块中)。

答案 1 :(得分:0)

您是否尝试将FileShare设置为写入

//     FileShare.Write Allows subsequent opening of the file for writing. If this flag is not specified,
//     any request to open the file for writing (by this process or another process)
//     will fail until the file is closed. However, even if this flag is specified,
//     additional permissions might still be needed to access the file.

using (FileStream fstream = new FileStream(imgPath, FileMode.Create, FileAccess.Write, FileShare.Write))
{
    encoder.Save(fstream);
    fstream.Close();
}