簡體   English   中英

我想用MemoryStream代替FileStream

[英]I want to use MemoryStream replace FileStream

我在添加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;                   
    }));
}

您可以添加標志以停止並行寫入同一文件。

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;
        }));

}

您需要注意錯誤處理,並確保設置reset標志(最好在finally塊中)。

您是否嘗試過將FileShare設置為Write

//     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();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM