[2005] MemoryStream TextWriter
Hi Guys,
Just having a small issue with a MemoryStream, I think my only real issue is lack of education.
I am wanting to dump a MemoryStream to a text file (.csv). Now I have some code here that does this but I'm left thinking there is a better or more elegant way to do this.
VB Code:
Private Sub StreamToFile(ByVal sFilePath As String, ByVal objStream As System.IO.MemoryStream)
Dim objTxtWriter As System.IO.TextWriter = Nothing
Dim objReader As System.IO.StreamReader = Nothing
Try
objTxtWriter = New System.IO.StreamWriter(sFilePath)
objReader = New System.IO.StreamReader(objStream)
objTxtWriter.Write(objReader.ReadToEnd())
objReader.Close()
objTxtWriter.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
If objTxtWriter IsNot Nothing Then
objTxtWriter.Dispose()
objTxtWriter = Nothing
End If
objReader.Dispose()
End Try
As you can see I am using a StreamReader to get the contents of the stream as a string and dump it. My gut feeling is that I should be able to dump this stream without using a reader?
Is the above method using a reader the only way? Can I feed a raw MemoryStream into a file??
I have done many searches but found only unlcear or incomplete answers.
Thanks PPL,
Matt.
Re: [2005] MemoryStream TextWriter
Try the WriteTo method of the MemoryStream. The help says:
Quote:
Writes the entire contents of this memory stream to another stream.
Re: [2005] MemoryStream TextWriter
Using Mr.No's suggestion:
VB Code:
Private Sub StreamToFile1(ByVal sFilePath As String, ByVal objStream As System.IO.MemoryStream)
Using sr As New IO.StreamWriter(sFilePath)
objStream.WriteTo(sr.BaseStream)
End Using
End Sub
or another way:
VB Code:
Private Sub StreamToFile2(ByVal sFilePath As String, ByVal objStream As System.IO.MemoryStream)
Dim count As Integer = Convert.ToInt32(objStream.Length)
Dim buffer(count - 1) As Byte
objStream.Read(buffer, 0, count)
IO.File.WriteAllBytes(sFilePath, buffer)
End Sub
Re: [2005] MemoryStream TextWriter
PEEEERRRRRRFECT!!!!!
That's exactly the sort of answer I was chasing. I knew there had to be a more elegant solution!
Thanks to the both of you, I had seen the WriteTo method but hadn't made the metal 'skip'.
Love your work JM!!!!! Love it!
Again thank you to you both...
Re: [2005] MemoryStream TextWriter
You could just use a FileStream and forget the StreamWriter too. In that case:
VB Code:
Using sr As New IO.StreamWriter(sFilePath)
objStream.WriteTo(sr.BaseStream)
End Using
would become:
VB Code:
Using fs As New IO.FileStream(sFilePath, IO.FileMode.Create)
objStream.WriteTo(fs)
End Using