© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•12mo ago•
53 replies
Hass

Converting json to MemoryStream and back breaks the json

For context, I have the following JSON (most of the stuff omitted for brevity):
{"schemaId":"azureMonitorCommonAlertSchema","data":{...}}
{"schemaId":"azureMonitorCommonAlertSchema","data":{...}}

After I convert it to a
MemoryStream
MemoryStream
and back to string, it surrounds the string with quotation marks and re-escapes the already-escaped characters.

Method used to convert to
MemoryStream
MemoryStream
:
internal static MemoryStream CreateMemoryStream(this string data)
{
  byte[] byteArray = Encoding.UTF8.GetBytes(data);
  MemoryStream stream = new(byteArray) { Position = 0 };
  return stream;
}
internal static MemoryStream CreateMemoryStream(this string data)
{
  byte[] byteArray = Encoding.UTF8.GetBytes(data);
  MemoryStream stream = new(byteArray) { Position = 0 };
  return stream;
}

I also tried using a
StreamWriter
StreamWriter
approach, but to no avail.


The snippet of code that converts the
MemoryStream
MemoryStream
back to
string
string
:
 using StreamReader reader = new(ms, encoding: System.Text.Encoding.UTF8, leaveOpen: true);
 string result = await reader.ReadToEndAsync();
 using StreamReader reader = new(ms, encoding: System.Text.Encoding.UTF8, leaveOpen: true);
 string result = await reader.ReadToEndAsync();


It results in the following broken JSON:
"{\"schemaId\":\"azureMonitorCommonAlertSchema\",\"data\":{...}}"
"{\"schemaId\":\"azureMonitorCommonAlertSchema\",\"data\":{...}}"


I can't pinpoint exactly why this is happening, I guess it has to do with the fact that when it reads it back to a
string
string
, because the content is already a "
string
string
", it escapes the already-escaped quotes and surrounds it with the quotemarks. I don't know how to avoid this behaviour tho.

Edit: change wording
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements
Next page

Similar Threads

✅ MemoryStream question
C#CC# / help
15mo ago
Iterating over AsyncEnumerable and writing to MemoryStream
C#CC# / help
3y ago
❔ Help needed converting anon object to JSON
C#CC# / help
3y ago