Determining the type of data pointed to by a Url – VB.NET version

Earlier today, I posted an example of some Visual C# code that checks the type of the data pointed to by a Url.  I was thinking that it might be nice to post a Visual Basic .NET equivalent...

This version is a direct port of the Visual C# code and comes with the same caveat:

"Please note: To keep this example as small as possible, only minimal error checking is performed - any real-world implementation would need to do much more than what I show here."

Imports System
Imports System.Net

module Module1

    sub Main(args as String())
        if(args.Length <> 1) then
            Console.WriteLine("Please specify a url path.")
        end if
        ' display the content type for the url
        Dim url as String = args(0)
        Console.WriteLine(String.Format("Url : {0}", url))
        Console.WriteLine(String.Format("Type: {0}", GetContentType(url)))

    end sub  
    function GetContentType(url as String) as String

        Dim response as HttpWebResponse = nothing
        Dim contentType as String = ""
            ' create the request
            Dim request as HttpWebRequest = CType(WebRequest.Create(url), HttpWebRequest)

            ' instruct the server to return headers only
            request.Method = "HEAD"

            ' make the connection
            response = CType(request.GetResponse(), HttpWebResponse)

            ' read the headers
            Dim headers as WebHeaderCollection = response.Headers

            ' get the content type
            contentType = headers("Content-type")

        catch e as WebException
            ' we encountered a problem making the request
            '  (server unavailable (404), unauthorized (401), etc)
            response = CType(e.Response, HttpWebResponse)

            ' return the message from the exception
            contentType = e.Message

        catch e as NotSupportedException
            ' this will be caught if WebRequest.Create encounters a uri
            '  that it does not support (ex: mailto)

            ' return a friendly error message
            contentType = "Unsupported Uri"

        catch e as UriFormatException
            ' the url is not a valid uri
            ' return a friendly error message
            contentType = "Malformed Uri"

            if not (response is nothing) then
            end if
        end try
        return contentType
    end function
end module

As with the Visual C# version, the above code can be compiled and run on either the .NET Framework or the .NET Compact Framework.

Take care,
-- DK

This posting is provided "AS IS" with no warranties, and confers no rights.

Skip to main content