Using C# and .net 4.8 I have an API method where users upload a file.
I save the file to a temp directory, do some processing, then save it to the final destination directory.
At the end of the process I want to delete the file from the temp directory, but I get an exception:
The process cannot access the file because it is being used by another process.
on this line:
File.Delete(originalTmpPath);
To narrow down the problem I have remmed out all code that does additional processing so now my code does only 3 things:
- Save the file to the temp directory.
- Save the file “In the temp directory” to another directory.
- Delete the first file
Here’ the code in the API:
HttpResponseMessage result = null;
var httpRequest = HttpContext.Current.Request;
var file = httpRequest.Files[0];
// Save image to temp folder
file.SaveAs(originalTmpPath);
// Save image to final folder
Bitmap bmp = new Bitmap(System.Drawing.Image.FromFile(originalTmpPath));
bmp.Save(originalPath);
//Exception here:
File.Delete(originalTmpPath);
Any idea how I can stop the process/unlock the file and delete it?
Thank you