EDIT: I finally found the error. It is totally irrelevant with the bitmaps or streams or static. It appears that one of my colleagues has forgotten to remove email attachment after sending the mail, and the mail attachment service keeps open. I used a using statement for whole mail sending process, and it is solved. Thanks everyone.
I know you might say that there are billions of threads with the same title and this is a duplicate, but believe me it is not. I have been searching for the solution like 7 hours, but nothing helped so far.
The problem is the following: This is a photo capture application which uses WebcamSource as the webcam. The application runs well when first photo is taken and emailed to user. However, when user returns to the process all over again (where it started before the first run), application gives such a error. The erroneous code is below.
public static void SaveImageCapture(BitmapSource bitmap)
{
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
// bitmap = BitmapFrame.Create(BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
encoder.Frames.Add(BitmapFrame.Create(bitmap));
encoder.QualityLevel = 100;
encoder.Rotation = Rotation.Rotate270;
try
{
using (FileStream fstream = new FileStream("Photos\\" + fileName + ".jpg", FileMode.Create))
{
encoder.Save(fstream);
fstream.Close();
}
}
catch (Exception e) {
System.Windows.Forms.MessageBox.Show(e.ToString());
}
}
Code crashes at FileStream fstream = new FileStream("Photos\\" + fileName + ".jpg", FileMode.Create)
and it gives the error
The process cannot access the file "C:\Users[username]\Dropbox[projectname][projectname]\bin\Debug\Photos" because it is being used by another process.
I tried closing webcam stream, surrounding the code with try/catch, putting it into using statement, adding FileAccess and FileShare fields, trying to add BitmapCreateOptions.None
and BitmapCacheOption.OnLoad
(it did not allow me), creating new images with different names rather than overwriting the same image, deleting image after sending email(it gave me the same error), and some small arrangements that may cause file access problems.