.NET Mail正在使用的文件

时间:2018-09-07 20:12:03

标签: vb.net email

我写了一个简单的程序来收集文件,发送文件,然后删除所说的文件。我正在使用System.Net.Mail

通过电子邮件发送它们
If Label6.Text = "" Then
        mail.Attachments.Add(New Attachment(zipPath))
    End If
    'Enables SSL, if required
    ssl = Provider.ssl
    If skipAhead = True Then
        ssl = True
    End If
    If ssl = True Then
        SmtpServer.EnableSsl = True
    End If
    'Sends the email
    SmtpServer.Send(mail)
    'Allows the user to either keep testing, or quit.
    If skipAhead = True Then
        My.Computer.FileSystem.DeleteFile(unalteredPath)
        My.Computer.FileSystem.DeleteFile(unalteredPath1)
        My.Computer.FileSystem.DeleteFile(zipPath)
    Else
        Dim keepOpen As Integer = MsgBox("The Email was sent. You can keep testing if you would like to. Press ok to close, and cancel to keep testing", MsgBoxStyle.OkCancel)
        If keepOpen = 1 Then
            Close()
        End If
    End If

如第2行所示,附件已添加到电子邮件中,在发送电子邮件之前,我不会尝试删除附件,但是,当代码运行时,它将引发错误,表明正在使用文件通过另一个过程。

我也想知道这是否会一直存在于创建的.zip中。这是执行此操作的代码:

Public Sub Zipping()
    'Copies files to the folder where they will be zipped from
    My.Computer.FileSystem.CopyFile(unalteredPath, outputs & "\ExIpOutput.txt")
    My.Computer.FileSystem.CopyFile(unalteredPath1, outputs & "\IpConfig.txt")
    'Deletes the old output files
    My.Computer.FileSystem.DeleteFile(unalteredPath)
    My.Computer.FileSystem.DeleteFile(unalteredPath1)
    'Starts the zip Sub
    ZipFile.CreateFromDirectory(outputs, zipPath, CompressionLevel.Fastest, True)
    My.Computer.FileSystem.DeleteDirectory(outputs, FileIO.DeleteDirectoryOption.DeleteAllContents)
End Sub

这是CreateFromDirectory子:

Public Shared Sub CreateFromDirectory(sourceDirectoryName As String, destinationArchiveFileName As String, compressionLevel As Compression.CompressionLevel, includeBaseDirectory As Boolean)
End Sub

这里是否缺少我的东西,还是需要让程序休眠一会儿才能发送电子邮件,然后删除.zip文件?

2 个答案:

答案 0 :(得分:3)

您可以将文件加载到数组中:https://github.com/spudmashmedia/swagger-complete-selfhosted.git

然后从中获取MemoryStream:File.ReadAllBytes(String) Method

最后,您可以将MemoryStream用于附件:How do I convert struct System.Byte byte[] to a System.IO.Stream object in C#?

由于要发送的数据在内存中,因此您应该能够删除该文件。请注意,如果发生崩溃,数据将消失。

示例在C#中,但是如果您在使用VB.NET中的方法时遇到问题,请编辑您的问题以显示您的知识并告诉我们问题出在哪里。

答案 1 :(得分:2)

对此问题的更好解决方案是处理锁定文件的Attachment对象。创建的任何具有Dispose方法的对象都应在对象处理完毕后调用该方法,而Attachment也不例外。

Dim fileAttachment As Attachment

If Label6.Text = "" Then
    fileAttachment = New Attachment(zipPath)
    mail.Attachments.Add(fileAttachment)
End If

'...

SmtpServer.Send(mail)

If fileAttachment IsNot Nothing Then
    fileAttachment.Dispose()
End If