I have checked other similar questions on SO and they either propose to use WebUtility.HtmlDecode() or replace the encoded parts character-by-character or assumes some known regex pattern, etc. They do not answer this specific query.
I have a C# console application, which posts some data to a MVC application. Then the message returned by the service is written to a simple text file. When I write it to the file, the text is like
"Something didn\u0027t work right while processing this request! \r\nSee detailed logs \u003e d:\\Sandboxes\\UGBNC\\Stage\\Logs\\ArgLog2087129002.log"
What I want is to remove these encoded texts like \u0027
, \r\n
, \\
etc. and format it properly (like, with new line, tab etc.) in my text file. And I don't know what all characters might come, so I cannot replace them with string replace
or regex replace
, I need a generic solution.
The MVC service returns the data as json with Content-Type: application/json; charset=utf-8
, and my client code is this
try
{
using (var client = new HttpClient())
{
var request = WebRequest.Create(uri);
//configure request details
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
var message = sr.ReadToEnd();
//process message
}
}
}
catch (WebException wex)
{
using (var stream = wex.Response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
var message = reader.ReadToEnd(); //this is the encoded string
File.AppendAllText("SomeTextFile.txt", message);
}
}
What is the best/simplest way to do this?
Note: I don't want to replace them character by character, I want a generic solution.