1

I have a method in a third-party tool that has the following criteria:

ExportToXML(fileName As String) 'Saves the content to file in a form of XML document

or

ExportToXML(stream As System.IO.Stream) 'Saves the content to stream in a form of XML document

How do I use the call with the stream as the parameter to get the XML as a string?

I have researched and tried several things and just still can't get it..

Chris
  • 33
  • 8

1 Answers1

4

You can use a MemoryStream as the stream to export the XML to, and then read the MemoryStream back with a StreamReader:

Option Infer On

Imports System.IO

Module Module1

    Sub Main()
        Dim xmlData As String = ""
        Using ms As New MemoryStream
            ExportToXML(ms)
            ms.Position = 0
            Using sr As New StreamReader(ms)
                xmlData = sr.ReadToEnd()
            End Using
        End Using

        Console.WriteLine(xmlData)
        Console.ReadLine()

    End Sub

    ' a dummy method for testing
    Private Sub ExportToXML(ms As MemoryStream)
        Dim bytes = Text.Encoding.UTF8.GetBytes("Hello World!")
        ms.Write(bytes, 0, bytes.length)
    End Sub

End Module

Added: Alternatively, as suggested by Coderer:

Using ms As New MemoryStream
    ExportToXML(ms)
    xmlData = Text.Encoding.UTF8.GetString(ms.ToArray())
End Using

A small effort at testing did not show any discernible efficiency difference.

Community
  • 1
  • 1
Andrew Morton
  • 24,203
  • 9
  • 60
  • 84
  • Could I read it straight into a StreamReader called sr and then do xml=sr.ReadToEnd()? Like, APublicProperty.ExportToXML(sr.BaseStream)... I'm new to working with streams so... – Chris Mar 27 '15 at 21:57
  • @Chris: No, you have to write to a Stream (or something that inherits Stream - like MemoryStream). StreamReader is **not** a Stream, it is a class that you use for reading from a stream. – Blackwood Mar 27 '15 at 22:39
  • @Chris I've put in an alternative way of getting the memorystream into a string from someone else's suggestion. I think that code is as short as it can be, given that ExportToXML is not a function. – Andrew Morton Apr 02 '15 at 18:20