If you're using C# 6
(Visual Studio 2015 or later), you can use an exception filter:
catch (WebException we) when (we.InnerException is SocketException)
{
var se = (SocketException)we.InnerException;
if (se.SocketErrorCode == SocketError.TimedOut)
{
...
}
}
catch (WebException we)
{
...
}
If you're using C# 7
(Visual Studio 2017), you can simplify that by combining an exception filter with pattern matching:
catch (WebException we) when (we.InnerException is SocketException se)
{
if (se.SocketErrorCode == SocketError.TimedOut)
{
...
}
}
catch (WebException we)
{
...
}
Or even:
catch (WebException we) when (we.InnerException is SocketException se && se.SocketErrorCode == SocketError.TimedOut)
{
...
}
catch (WebException we)
{
...
}
In earlier versions, C# didn't support exception filters. You'll have no choice but to catch the outer exception and test the inner exception:
catch (WebException we)
{
var se = we.InnerException as SocketException;
if (se != null)
{
if (se.SocketErrorCode == SocketError.TimedOut)
{
...
}
}
else
{
...
}
}