Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell Close File/Delete File After Emailing via .NET

I'm stuck at the end of a script I am working on where a file is emailed out before being deleted. Except.. the file seems to be still be opened, likely by the SMTP client, so I get an error when I try to delete it. Of course restarting a shell will let me delete it, thats not the point. ;-) Point is I'd like to create it, email it, delete it, in one script.

The Error:

   Cannot remove item C:\Temp\myfile.csv: The process cannot access the file
    'C:\Temp\myfile.csv' because it is being used by another process.

Code:

$emailFrom = 'noreply@localhost'
$emailTo = 'aaron@localhost'
$smtpServer = 'localhost'

$FileName='myfile.csv'
$FilePathName='c:temp\' + $FileName

$subject = 'Emailing: ' + $FileName
$body = 'This message as been sent with the following file or link attachments: ' + $FileName

$msg = new-object Net.Mail.MailMessage
$att = new-object Net.Mail.Attachment($FilePathName)
$smtp = new-object Net.Mail.SmtpClient($smtpServer)

$msg.From = $emailFrom
$msg.To.Add($emailTo)
$msg.Subject = $subject
$msg.Body = $body
$msg.Attachments.Add($att)
$smtp.Send($msg)

#Garbage Collection (used for releasing file for deleting)
# Start-Sleep -s 1
# [GC]::Collect()

#Clean-up/Remove File
# Start-Sleep -s 1
if (Test-Path $FilePathName) {Remove-Item $FilePathName}

The lines commented out are my attempts at injecting pauses and garbage cleanup, which yielded the same result.

like image 789
Aaron Wurthmann Avatar asked Nov 30 '10 23:11

Aaron Wurthmann


1 Answers

Dispose the attachment and email objects

$att.Dispose();
$msg.Dispose();

doing a GC won't help, as you still have root refs

like image 117
Scott Weinstein Avatar answered Oct 17 '22 04:10

Scott Weinstein