title: How do I delete the images from a folder after they have been used as the source for a PictureBox?
body: <p><a href="https://stackoverflow.com/questions/38825962/c-sharp-windows-forms-how-to-programmatically-set-image-preview-for-file-folde">Link to my previous question, which gives background to the situation</a></p>
  
  <p>I answered my own question above by programmatically changing images from the tempory folder where attachments are saved. This caused a new issue for me when fixing my own problem that I feel is too separate from the former.</p>
  
  <p>As my program closes, I delete the images from the temporary directory. Since I have got the preview to work fine upon clicking on the different images. I get the following error when trying to close the program (the deleting of images happens on this event):</p>
  
  <blockquote>
    <p>The process cannot access the file 'c:\temp\DigitalArchive\FILENAME.jpg' because it is being used by another process.</p>
  </blockquote>
  
  <p>So I have attempted to resolve it by clearing the picture from the temp folder before hand via:</p>
  
  <pre><code>if (picAttachPreview.Image != null)
          {
              picAttachPreview.Image.Dispose();
              picAttachPreview.Refresh();
          }
  
          //Runs through each file in the temporary directory and removes them to clear folder
          foreach (string item in Directory.GetFiles(tempfolder))
          {
              File.Delete(item);
          }
  </code></pre>
  
  <p><strong>Edit:</strong> I feel I should show where the image is updated for reference:</p>
  
  <pre><code>if (chkAttachments.Text.Contains(".jpg"))
          {
              var selectedImage = chkAttachments.Text;
              picAttachPreview.Image = Image.FromFile(Path.Combine(tempfolder, selectedImage));
          }
  </code></pre>