Search code examples
c#fileio

How to delete any dynamically created file from solution?


I am creating a file into the solution's directory as below:

var targetPathToCreate = Path.Combine(HttpRuntime.AppDomainAppPath, "FolderName");

DirectoryInfo dirInfo = new DirectoryInfo(targetPathToCreate);

if (!dirInfo.Exists)
{
    dirInfo.Create();
}

var filePath = Path.Combine(targetPathToCreate, "FileName");
System.IO.File.WriteAllBytes(filePath, bytesArray);

and further I am sending this document via email and then trying to delete this document.

For that I tried this code:

System.IO.File.Delete("FilePath");

but this line throws an exception:

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

Is there any way to delete the files by overcoming the exception?


Solution

  • You can use garbage collector's WaitForPendingFinalizers function. It will suspend the current thread until the thread that is processing the queue of finalizers has emptied that queue.

       if (System.IO.File.Exists(filePath))
        {
          System.GC.Collect();
          System.GC.WaitForPendingFinalizers();
          System.IO.File.Delete(filePath);
        }
    

    If this doesn't work, you have to dispose your mail object.

    mail.Attachments.Add(...);
    smtpServer.Send(mail);
    mail.Dispose();
    System.IO.File.Delete(filePath);