Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

View content of a Stream in Visual Studio's QuickWatch window

How do I view the content of a Stream in the QuickWatch window within Visual Studio?

Update

As per Daniel's answer I used the following code -

System.Text.Encoding.UTF8.GetString((byte[])stream.GetType().GetMethod("InternalGetBuffer", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).Invoke(stream, null))

like image 873
jameskind Avatar asked Oct 13 '11 14:10

jameskind


People also ask

How do I get a watch window in Visual Studio?

It's available from Debug | Windows | Watch | Watch 1 or Ctrl + Alt + W + 1. There are 4 watch windows in Visual Studio, which you can use in different contexts (Watch 1, Watch 2, etc.). Any expression can be entered into the watch window.

How do I get immediate window in Visual Studio?

On the Debug menu, choose Windows > Immediate.

How do I see return value in Visual Studio?

View return values for functions If the window is closed, use Debug > Windows > Autos to open the Autos window. In addition, you can enter functions in the Immediate window to view return values. (Open it using Debug > Windows > Immediate.)


2 Answers

You can view the content of the MemoryStream without altering it when you can make some assumptions:

  1. Your stream indeed is a MemoryStream
  2. Your stream contains only string data
  3. You know the encoding of that string, e.g. UTF8 or ASCII

If you can make these assumptions, you can use the following code in your Watch window:

System.Text.Encoding.UTF8.GetString((byte[])stream.GetType().GetMethod("InternalGetBuffer", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).Invoke(stream, null))

Disclaimer:
This might have side effects I haven't thought of or might throw an exception in certain circumstances, so don't use this in production code.

like image 186
Daniel Hilgarth Avatar answered Nov 15 '22 05:11

Daniel Hilgarth


I don't believe there's anything generic built in, since QuickWatch is not generally designed to affect the state of what's being watched, and reading from a stream inherently alters the internal state (e.g. the current position) - even assuming that the stream can be read.

And even then, not all streams support seeking, so reading from the stream would then make the read data unavailable for the actual program, with no means to recover that data.


In limited circumstances, if you construct the MemoryStream from a byte buffer, or if GetBuffer() is applicable, a watch on the byte buffer would be doable, rather than trying to watch the stream.

like image 31
Damien_The_Unbeliever Avatar answered Nov 15 '22 05:11

Damien_The_Unbeliever