I have problem with add Image
, I can add one time, if i add two or more add it error:
The process cannot access the file 'C:\\Users\\Administrator\\AppData\\Roaming\\afinos\\CaptureImage\\CapImage.Jpg' because it is being used by another process.I use following:
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;
}));
}
You can add flag to stop parallel writes to the same file.
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;
}));
}
You need to take care of error handling and make sure to set reset the flag (preferably in finally block).
Have you tried setting the FileShare
to 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();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.