Free Support Forum -

SaveToStream and emailing as attachment

I am using the following code to generate some test files and email. When the email arrives, it has the attachment, but it is 0 size. Anyone have an idea?

Sub TestProcess(ByVal _times As Long)

Dim _book As New Workbook

'Build a sampe data table
Dim _dt As DataTable = SampleData()

For i As Long = 1 To _times
Dim _sheet As Worksheet = _book.Worksheets(0)
_sheet.Cells.ImportDataTable(_dt, False, "A1")

Dim s As System.IO.Stream = Nothing
s = _book.SaveToStream

SendEmail(s, "test.xls")


End Sub

Private Function SampleData() As DataTable
Dim _dt As New DataTable
Dim _dr As DataRow


For i As Integer = 1 To 5
_dr = _dt.NewRow

_dr("row") = i.ToString
_dr("model") = "Model" & i.ToString
_dr("serial") = "Serial" & i.ToString
_dr("type") = "type" & i.ToString
_dr("last") = "Last" & i.ToString


Return _dt

End Function

Private Sub SendEmail(ByVal _stream As System.IO.Stream, ByVal _name As String)
Dim _body As New System.Text.StringBuilder
With _body
.AppendLine("body {font-family: Verdana, Arial; font-size: 8pt;}")
.AppendLine("Please complete the attached spreadsheet return via fax or email.

End With

Dim _msg As New MailMessage
With _msg
.Subject = "Test Request"
.IsBodyHtml = True
.Body = _body.ToString
.Attachments.Add(New Attachment(_stream, _name, "application/"))

.From = New MailAddress("", "Test Request")

.To.Add(New MailAddress("", "Me"))

End With

Dim smtp As New SmtpClient
smtp.Host = SomeServer

End Sub

Got it - I needed to add a s.Postion = 0