Madhav
Madhav

Reputation: 569

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?

Upvotes: 0

Views: 227

Answers (2)

Thilina Koggalage
Thilina Koggalage

Reputation: 1084

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);

Upvotes: 3

Hounddog75
Hounddog75

Reputation: 75

I took a look and noticed that the error is possibly generated because your code System.IO.File.WriteAllBytes(filePath, bytesArray); may not be finished in its execution.

Here is a resource you can look at. You could also get the newly generated file's name by writing a new method that mails it and then deletes it, which could include something like this:

System.IO.FileInfo fi = new System.IO.FileInfo(@"C:\MyFiles\" + yourfilename + "'");
        try
        {
            fi.Delete();
        }

Upvotes: 0

Related Questions