Question

Is there a way to determine if the response from an HttpWebRequest in C# contains binary data vs. text? Or is there another class or function I should be using to do this?

Here's some sample code. I'd like to know before reading the StreamReader if the content is not text.

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.someurl.com");
request.Method = WebRequestMethods.Http.Get;
using (WebResponse response = request.GetResponse())
{
    // check somewhere in here if the response is binary data and ignore it 
    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
    {
        string responseDetails = reader.ReadToEnd().Trim();
    }
}
Was it helpful?

Solution

In general, web sites will tell you in the Content-Type header what kind of data they're returning. You can determine that by getting the ContentType property from the response.

But sites have been known to lie. Or not say anything. I've seen both. If there is no Content-Type header or you don't want to trust it, then the only way you can tell what kind of data is there, is by reading it.

But then, if you don't trust the site, why are you reading data from it?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top