0

I upload a file and check file exist with same name in target folder and delete if it exist. But the line I point above throws an exception with

"Cant access the file... because it is being used by another process"

message. Here is the code

public ActionResult Upload(int? chunk, string name)
{
    string fileExtension = Path.GetExtension(name);
    if (fileExtension != ".csv" && fileExtension != ".xml"){
        return Json(new {
            Success=false,
            Message = "<b>Invalid file type</b>"
        }, JsonRequestBehavior.AllowGet); 
    }

    var fileUpload = Request.Files[0];
    string fullName = Path.Combine(HttpRuntime.AppDomainAppPath, "App_Data", fileUpload.FileName);
    if (System.IO.File.Exists(fullName))
        System.IO.File.Delete(fullName);// throws exception.
}
Mong Zhu
  • 23,309
  • 10
  • 44
  • 76
TyForHelpDude
  • 4,828
  • 10
  • 48
  • 96
  • `File.Exists` is *redundant*: https://msdn.microsoft.com/en-us/library/system.io.file.delete(v=vs.110).aspx "If the file to be deleted does not exist, no exception is thrown." – Dmitry Bychenko Jul 06 '16 at 09:30
  • When you manipulate File, make sure all method are closed. buffer, reader, writer, IDocument, etc... I had same issue than you 1 week ago. – Alexis Jul 06 '16 at 09:30
  • "Delete does not delete a file that is open for normal I/O or a file that is memory mapped." – Dmitry Bychenko Jul 06 '16 at 09:31
  • antivirus software is a popular culprit for locked files. it's important to check a file for viruses before deleting it :) – ths Jul 06 '16 at 09:41
  • Possible duplicate of [How can I delete a file that is in use by another process?](http://stackoverflow.com/questions/5232647/how-can-i-delete-a-file-that-is-in-use-by-another-process) – default Jul 06 '16 at 09:42
  • @Alexis this method runs directly after upload a file from ui.. – TyForHelpDude Jul 06 '16 at 09:46
  • @ths no antivir running – TyForHelpDude Jul 06 '16 at 09:47

1 Answers1

3

The error is pretty self-explanatory. The file you're trying to delete is already being used by another process. Check if it's you who's using that file or some other process.

If it's you who's using it, make sure you close every reader you opened.

Haytam
  • 4,643
  • 2
  • 20
  • 43
  • No reader exist, you see its upload method and check file condition executes first.. but yeah.. in page load function I read the existing file but not close it :D Thanks – TyForHelpDude Jul 06 '16 at 09:50