Visual Studio debugging tip: write contents of a variable to a file during your debugging session

Posted: (EET/GMT+2)

 

Visual Studio's debugger provides great debugging features, such as allowing you to view variable values while you're stepping through your code. Sometimes however, it would be useful to be able to save variable contents to disk (file) for later investigation. There's no ready-made function for this, but you can use the Immediate Window to do this.

To illustrate this, assume you're writing a web application that fetches data from another system using a REST API. In return, you get a string of JSON data, but since there's lots of data, you want to store the data into a file. While you're stopped for a breakpoint in the correct code location, open up the Immediate Window, and type in a command like this:

System.IO.File.WriteAllText(@"C:\Temp\Data.json", jsonResponse)

At the end of the line, press Enter. If all goes well, the Immediate Window responds like this:

Expression has been evaluated and has no value

Now the file "Data.json" should have been created in C:\Temp! You can use this same WriteAllText method to write more complex objects. An easy way is to first serialize data to JSON (using Newtonsoft's serializer) or XML, for instance. Then, get the serialized string, and write that to a file of your choosing.

Hope this helps!