How to solve "The process cannot access file due to opened already" without using statement

Posted by Dharmraj under C# category on | Points: 40 | Views : 1696
Some times you need to check whether file is exists or not? If exists then delete it and upload new file.

In this scenario File.Exists() became true then it holds the file object and after execution of that line if you are accessing that file, application will throw exception of "The process cannot access file due to opened already".

Here you cannot use using(){} statement.
The solution is to manually call garbage collector to make dispose objects.

private void SaveFile(string savePath, HttpPostedFile postedFile)
savePath = HttpContext.Current.Server.MapPath(savePath);

string fileName = postedFile.FileName;
if (File.Exists(Path.Combine(savePath, fileName)))
File.Delete(Path.Combine(savePath, fileName));
if (!Directory.Exists(savePath))
postedFile.SaveAs(Path.Combine(savePath, fileName));

Comments or Responses

Login to post response