I was trying to copy a file, and then delete it, as shown in code below, but kept getting System.IO.IOException "The process cannot access the file [filename] because it is being used by another process."
File.Copy(sourcefilename, targetfilename);
File.Delete(sourcefilename)
This was in a Windows Form application where the source file was a JPEG image that was at that moment being displayed in a PictureBox control. I eventually determined that the 'process' using the file was the PictureBox, so I had to find a way to detach the file from the control.
I am answering my own question here, after I figured out the answer, so please don't tell me to use File.Move instead. I had a good reason to first use File.Copy and then afterwards File.Delete.
To explain why I was doing it this way, instead of File.Move: because based on user input I might need to copy the file to more than one other location (different folders). So I had to keep the original file in its original location until all requested copying was complete, and only then delete the original file.
I first tried replacing the PictureBox's image with one in an ImageList, unconnected with the file I had copied:
PictureBox.Image = ImageList.Images[0];
Now, I would have thought that putting another image into the Image property of the control would release the PictureBox's hold on the file, but no. Not even directly assigning another image file to the control released it. I the tried both of the following, but neither worked:
PictureBox.Refresh();
PictureBox.Dispose();
Finally, I wondered if maybe the Image property had a method that might release the file, and Yes, it had a Dispose method, which finally worked to get the PictureBox to release the file.
File.Copy(sourcefilename, targetfilename);
PictureBox.Image.Dispose(); // <-- THIS DID THE TRICK
File.Delete(sourcefilename)
After this, the Delete method worked as desired. I did end up using an ImageList to put a neutral image in the PictureBox until the user selected a new image from a list.