0

When I try to delete a file, i got this error :

The process cannot access the file ' ' because it is being used by another process.

Here is my code :

   var file = Request.Files[0];
    file.SaveAs(path);
    
    ** Some tasks
    
    System.IO.File.Delete(path);

Any idea how can i resolve it ?

user1187282
  • 1,137
  • 4
  • 14
  • 23
  • 1
    Does this answer your question? [IOException: The process cannot access the file 'file path' because it is being used by another process](https://stackoverflow.com/questions/26741191/ioexception-the-process-cannot-access-the-file-file-path-because-it-is-being) – Prasad Telkikar Feb 18 '22 at 11:42
  • If you don't own the process that is locking the file open, and cannot force it to quit you might need to [register the file to be deleted at system restart instead](https://stackoverflow.com/questions/6077869/movefile-function-in-c-sharp-delete-file-after-reboot) – Caius Jard Feb 18 '22 at 12:17

1 Answers1

1

The problem here might be, that you are still have the file opened in your process and you somehow need to dispose it first. So you could do something like this:

    using (File.Create(@"yourlocation\filePath"))
    {
        //do something
    }
    File.Delete(@"yourlocation\filePath");

The using statement disposes the resource you are using automatically after the brackets finish.

Piepe
  • 98
  • 4