coreproxies.com

Home / Help Center / C# and VB.NET

Using Core Proxies with C# and VB.NET

In .NET a proxy is a WebProxy object with a NetworkCredential attached. This article shows it with HttpClient in C# and VB.NET, adds sticky sessions and SOCKS5, and includes the HttpWebRequest form for .NET Framework projects.

6 min readC# · VB.NET

The proxy string

Your dashboard shows each proxy as four parts separated by colons:

HOST:PORT:USERNAME:PASSWORD

HOST, PORT, USERNAME and PASSWORD are placeholders in every example below. Replace them with the values from your dashboard before you run the code. On Residential, Unlimited Residential and the mobile plans, HTTP, HTTPS and SOCKS5 use the same host and port.

HttpClient with WebProxy

This console program splits the string, builds the proxy, sends one request and prints the exit IP. Both versions run on .NET 6 and later, and on .NET Framework 4.7.2 and later with a reference to System.Net.Http.

C#

using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    private const string ProxyString = "HOST:PORT:USERNAME:PASSWORD";

    static void Main()
    {
        // host:port:username:password (the limit of 4 keeps a colon inside the password intact)
        string[] parts = ProxyString.Split(new[] { ':' }, 4);

        var proxy = new WebProxy("http://" + parts[0] + ":" + parts[1])
        {
            Credentials = new NetworkCredential(parts[2], parts[3])
        };

        var handler = new HttpClientHandler { Proxy = proxy, UseProxy = true };

        using (var client = new HttpClient(handler))
        {
            client.Timeout = TimeSpan.FromSeconds(30);
            try
            {
                string body = client.GetStringAsync("https://api.ipify.org?format=json").GetAwaiter().GetResult();
                Console.WriteLine(body);
            }
            catch (HttpRequestException ex)
            {
                Console.WriteLine("Request failed: " + ex.Message);
            }
            catch (TaskCanceledException)
            {
                Console.WriteLine("Timed out");
            }
        }
    }
}

VB.NET

Imports System.Net
Imports System.Net.Http
Imports System.Threading.Tasks

Module Program
    Private Const ProxyString As String = "HOST:PORT:USERNAME:PASSWORD"

    Sub Main()
        ' host:port:username:password (the limit of 4 keeps a colon inside the password intact)
        Dim parts As String() = ProxyString.Split(New Char() {":"c}, 4)

        Dim proxy As New WebProxy("http://" & parts(0) & ":" & parts(1)) With {
            .Credentials = New NetworkCredential(parts(2), parts(3))
        }

        Dim handler As New HttpClientHandler() With {
            .Proxy = proxy,
            .UseProxy = True
        }

        Using client As New HttpClient(handler)
            client.Timeout = TimeSpan.FromSeconds(30)
            Try
                Dim body As String = client.GetStringAsync("https://api.ipify.org?format=json").GetAwaiter().GetResult()
                Console.WriteLine(body)
            Catch ex As HttpRequestException
                Console.WriteLine("Request failed: " & ex.Message)
            Catch ex As TaskCanceledException
                Console.WriteLine("Timed out")
            End Try
        End Using
    End Sub
End Module

The output is a short JSON object such as {"ip":"203.0.113.24"}. On Residential and Rotating Mobile, a username without a session gets a new IP with every new connection.

In a real application, create one HttpClient per proxy configuration and reuse it. HttpClient keeps connections open, and requests sent over an open connection share its exit IP. If you need a new address for every request, send the header Connection: close by setting ConnectionClose to true on the client's DefaultRequestHeaders.

Sticky session

To hold one IP across requests, add a session number and a TTL in seconds to the username: USERNAME-session-482913-ttl-600 keeps one IP for 600 seconds. On Residential and Unlimited Residential a sticky session lasts up to 24 hours. The helper below picks a six-digit session number and returns a ready proxy object.

C#

using System;
using System.Net;

static class ProxyFactory
{
    private static readonly Random Rng = new Random();

    public static WebProxy CreateStickyProxy(string host, int port, string user, string password, int ttlSeconds)
    {
        int sessionId = Rng.Next(100000, 1000000);
        string stickyUser = user + "-session-" + sessionId + "-ttl-" + ttlSeconds;

        return new WebProxy("http://" + host + ":" + port)
        {
            Credentials = new NetworkCredential(stickyUser, password)
        };
    }
}

VB.NET

Imports System.Net

Module ProxyFactory
    Private ReadOnly Rng As New Random()

    Function CreateStickyProxy(host As String, port As Integer, user As String, password As String, ttlSeconds As Integer) As WebProxy
        Dim sessionId As Integer = Rng.Next(100000, 1000000)
        Dim stickyUser As String = user & "-session-" & sessionId.ToString() & "-ttl-" & ttlSeconds.ToString()

        Return New WebProxy("http://" & host & ":" & port.ToString()) With {
            .Credentials = New NetworkCredential(stickyUser, password)
        }
    End Function
End Module

Pass the result to HttpClientHandler.Proxy as in the first example; a TTL of 600 gives a ten-minute session. Call the function again to get a new session number and a different IP, and give each account or task its own number.

Datacenter and ISP orders work differently: choose rotating, sticky or static in the Proxy generator of your order and copy the generated lines into ProxyString.

SOCKS5

From .NET 6 onward, WebProxy accepts a SOCKS5 address. Change the scheme and leave the rest of the program as it is.

C#

var proxy = new WebProxy("socks5://HOST:PORT")
{
    Credentials = new NetworkCredential("USERNAME", "PASSWORD")
};

VB.NET

Dim proxy As New WebProxy("socks5://HOST:PORT") With {
    .Credentials = New NetworkCredential("USERNAME", "PASSWORD")
}

.NET Framework does not support SOCKS proxies in WebProxy; use the http:// form there.

HttpWebRequest on .NET Framework

Older projects often use HttpWebRequest. The proxy object is the same; assign it to the request.

C#

using System;
using System.IO;
using System.Net;

class Program
{
    static void Main()
    {
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

        var proxy = new WebProxy("http://HOST:PORT")
        {
            Credentials = new NetworkCredential("USERNAME", "PASSWORD")
        };

        var request = (HttpWebRequest)WebRequest.Create("https://api.ipify.org?format=json");
        request.Proxy = proxy;
        request.Timeout = 30000;

        try
        {
            using (var response = (HttpWebResponse)request.GetResponse())
            using (var reader = new StreamReader(response.GetResponseStream()))
            {
                Console.WriteLine((int)response.StatusCode + " " + reader.ReadToEnd());
            }
        }
        catch (WebException ex)
        {
            Console.WriteLine("Request failed: " + ex.Message);
        }
    }
}

VB.NET

Imports System.IO
Imports System.Net

Module Module1
    Sub Main()
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12

        Dim proxy As New WebProxy("http://HOST:PORT") With {
            .Credentials = New NetworkCredential("USERNAME", "PASSWORD")
        }

        Dim request = CType(WebRequest.Create("https://api.ipify.org?format=json"), HttpWebRequest)
        request.Proxy = proxy
        request.Timeout = 30000

        Try
            Using response = CType(request.GetResponse(), HttpWebResponse)
                Using reader As New StreamReader(response.GetResponseStream())
                    Console.WriteLine(CInt(response.StatusCode) & " " & reader.ReadToEnd())
                End Using
            End Using
        Catch ex As WebException
            Console.WriteLine("Request failed: " & ex.Message)
        End Try
    End Sub
End Module

The SecurityProtocol line matters on .NET Framework versions that do not enable TLS 1.2 by default. HttpWebRequest still works on current .NET, but Microsoft recommends HttpClient for new code.

Errors you may see

MessageMeaningWhat to check
407 Proxy Authentication RequiredThe proxy rejected the credentialsThe Credentials property is set on the WebProxy; username with its session suffix; plan still active
No such host is knownThe proxy hostname did not resolveThe host copied from your dashboard; the scheme is included in the proxy address
Invalid URI: Invalid port specifiedA placeholder is still in the addressHOST and PORT replaced with the values from your dashboard
TaskCanceledExceptionThe request exceeded the timeoutThe port shown in your dashboard; outbound firewall rules; a longer Timeout for slow targets
The same IP on every requestThe connection is being reusedSet ConnectionClose to true, or create a new client

To rule out the code, test the same proxy from the command line first: see testing a proxy on Windows. The same request in Python is in the Python article.

Run it against your own plan

Paste the host, port, username and password from your dashboard into the constants at the top of each example. Residential packages start at 5 GB for €11.50, excluding VAT.