Write the whole memory stream into the stream writer

StewartBW 1,805 Reputation points
2024-08-15T09:50:17.7933333+00:00

Hello experts

How to write the whole contents of a memory stream which is some text into my stream writer?

On a separate note, I need to write one single text line and then the whole contents of memory stream which is also text into a system file, in a loop.

Which writer to choose to get the best performance? stream writer or binary writer?

I tested binary writer, but each time I call its .Write("Some String") it adds an empty space initial unwanted character to the beginning of the line :(

Thanks for the help :)

  • .net fw 4.0 full profile
Developer technologies VB
Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. Jiachen Li-MSFT 34,221 Reputation points Microsoft External Staff
    2024-08-16T01:35:59.43+00:00

    Hi @StewartBW ,

    1. StreamWriter is optimized for writing text and handles encoding automatically. It is the best choice when you need to work with textual data, such as writing strings to a file.
    2. BinaryWriter is designed for writing primitive types in binary form. When you use BinaryWriter.Write("Some String"), it writes additional metadata (like the length of the string) and possibly other information, which is why you might see extra characters or spaces. It’s not suitable for pure text writing.
       Using memoryStream As New MemoryStream()
           memoryStream.Position = 0 
           Using streamReader As New StreamReader(memoryStream)
               Using streamWriter As New StreamWriter("output.txt")
                   streamWriter.WriteLine("one single text line")
                   streamWriter.Write(streamReader.ReadToEnd())
               End Using
           End Using
       End Using
    

    Best Regards.

    Jiachen Li


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2024-08-15T20:30:29.2766667+00:00

    a StreamWriter() is for writing string or char[] values to stream. its default encoder is UTF-8 no BOM. a BinaryStream is for writing byte buffers. if a char[] or string is passed, it is internally converted to a byte[] based on the Encoding specified in the constructor (UTF-8 BOM is the default). the extra char is the BOM.

    https://en.wikipedia.org/wiki/Byte_order_mark

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.