Reputation: 1048
I have a URL. Now I want to find out the content of the URL. By content of the URL I mean whether the URL contains a html page, video or an image/photo. How can I do this in asp.net with c#.
Upvotes: 2
Views: 1500
Reputation: 77304
For easier testing, this is a console application, but it should work with ASP.NET all the same:
namespace ConsoleApplication1
{
using System;
using System.Net;
class Program
{
static void Main()
{
//var request = WebRequest.Create("https://www.google.com"); // page will result in html/text
var request = WebRequest.Create(@"https://www.google.de/logos/2013/douglas_adams_61st_birthday-1062005.2-res.png");
request.Method = "HEAD"; // only request header information, don't download the whole file
var response = request.GetResponse();
Console.WriteLine(response.ContentType);
Console.WriteLine("Done.");
Console.ReadLine();
}
}
}
Upvotes: 0
Reputation: 134005
The easiest way would be to do a HEAD request with HttpWebRequest
:
var req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "HEAD";
using (var response = (HttpWebResponse)req.GetResponse())
{
// Here, examine the response headers.
// In particular response.ContentType
}
In some cases, HEAD might give you a 405 error, meaning that the server doesn't support HEAD.
In that case, just do a GET request (change req.Method = "GET"
). That will start to download the page, but you can still view the content type header.
Upvotes: 5
Reputation: 499052
Except from following the link, fetching the result and figuring out from the file content what file it is (which is rather tricky), there is no fool proof way.
You can try to determine from the file extension or the returned content-type
header (you can issue a HEAD
request) what the type should be. This will tell you what the server claims the file type to be.
Upvotes: 0
Reputation: 101614
Probably start off using a WebClient
and visit/download the page. Then use an HTML parser, and whatever method you deem best, to determine what kind of content is on the page.
Upvotes: 0