user1187282
user1187282

Reputation: 1237

How to delete properly a file in C#

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 ?

Upvotes: 0

Views: 406

Answers (1)

Piepe
Piepe

Reputation: 108

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.

Upvotes: 1

Related Questions