How do I clear System.Net client DNS cache?
Solution 1:
I finally dug up the obscure command from MSDN that fixes this:
ServicePointManager.DnsRefreshTimeout = 0;
As I unwound all the weird things I'd tried previously, I discovered one other setting that I need along with the one above; on the request object, turn off keep-alive:
request.KeepAlive = false;
Solution 2:
A late answer to be sure, but I found this solution worked better than the accepted answer. In my scenario I am testing SQL connections, and I couldn't apply the existing answer since I have no request.KeepAlive
to set.
This page by Brian Mancini ("derp turkey") details his adventure in clearing the DNS cache. Full props to him, I'm just adding his solution here:
public class DnsUtils
{
[DllImport("dnsapi.dll", EntryPoint="DnsFlushResolverCache")]
static extern UInt32 DnsFlushResolverCache();
[DllImport("dnsapi.dll", EntryPoint = "DnsFlushResolverCacheEntry_A")]
public static extern int DnsFlushResolverCacheEntry(string hostName);
public static void FlushCache()
{
DnsFlushResolverCache();
}
public static void FlushCache(string hostName)
{
DnsFlushResolverCacheEntry(hostName);
}
}
Solution 3:
If you want to keep the DnsRefreshTimeout > 0 then you can update the cache by making a call to:
System.Net.Dns.GetHostEntry("example.com");
Solution 4:
you could use System.Diagnostics.Process to launch ipconfig /flushdns