Networking in C#

The .NET Framework provides a layered, extensible, and managed implementation of networking services that you can easily integrate into your applications. The System.Net namespace contains classes for network communication, web requests, DNS operations, and secure connections.

Syntax

To use networking classes, include the System.Net namespace −

using System.Net;

Creating a URI and web request −

Uri uri = new Uri("http://www.example.com/");
WebRequest request = WebRequest.Create(uri);

Using Uri Class

The Uri class in C# provides object representation of a uniform resource identifier (URI). It helps parse and manipulate web addresses −

using System;

class Program {
    static void Main() {
        Uri uri = new Uri("https://www.example.com/page?id=123");
        
        Console.WriteLine("Original URI: " + uri.ToString());
        Console.WriteLine("Scheme: " + uri.Scheme);
        Console.WriteLine("Host: " + uri.Host);
        Console.WriteLine("Path: " + uri.AbsolutePath);
        Console.WriteLine("Query: " + uri.Query);
    }
}

The output of the above code is −

Original URI: https://www.example.com/page?id=123
Scheme: https
Host: www.example.com
Path: /page
Query: ?id=123

Using WebRequest Class

The WebRequest class is used to make HTTP and HTTPS requests. The System.Net classes automatically handle SSL encryption when the URI begins with "https:" −

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

class Program {
    static void Main() {
        try {
            Uri uri = new Uri("https://httpbin.org/get");
            WebRequest request = WebRequest.Create(uri);
            request.Method = "GET";
            
            WebResponse response = request.GetResponse();
            Stream dataStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream);
            
            string responseData = reader.ReadToEnd();
            Console.WriteLine("Response received successfully");
            Console.WriteLine("Content length: " + response.ContentLength);
            
            reader.Close();
            response.Close();
        }
        catch (Exception e) {
            Console.WriteLine("Error: " + e.Message);
        }
    }
}

The output of the above code is −

Response received successfully
Content length: -1

DNS Operations

The Dns class provides methods to retrieve host information and resolve domain names to IP addresses −

using System;
using System.Net;

class Program {
    static void Main() {
        string hostName = Dns.GetHostName();
        Console.WriteLine("Hostname: " + hostName);
        
        IPHostEntry hostEntry = Dns.GetHostEntry(hostName);
        IPAddress[] addresses = hostEntry.AddressList;
        
        for (int i = 0; i < addresses.Length; i++) {
            Console.WriteLine("IP Address " + (i + 1) + ": " + addresses[i].ToString());
        }
    }
}

The output of the above code is −

Hostname: DESKTOP-ABC123
IP Address 1: 192.168.1.100
IP Address 2: ::1

FTP Operations with SSL

For FTP operations with SSL encryption, use the FtpWebRequest class and set the EnableSsl property to true

using System;
using System.Net;

class Program {
    static void Main() {
        try {
            string ftpUri = "ftp://ftp.example.com/testfile.txt";
            FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create(ftpUri);
            
            ftpRequest.EnableSsl = true;
            ftpRequest.Method = WebRequestMethods.Ftp.GetFileSize;
            ftpRequest.Credentials = new NetworkCredential("username", "password");
            
            Console.WriteLine("FTP request configured with SSL");
            Console.WriteLine("Method: " + ftpRequest.Method);
            Console.WriteLine("SSL Enabled: " + ftpRequest.EnableSsl);
        }
        catch (Exception e) {
            Console.WriteLine("FTP Error: " + e.Message);
        }
    }
}

The output of the above code is −

FTP request configured with SSL
Method: SIZE
SSL Enabled: True

Common Networking Classes

Class Purpose
WebRequest Base class for making HTTP/HTTPS requests
WebResponse Represents the response from a web request
Uri Object representation of a uniform resource identifier
Dns Provides domain name resolution services
FtpWebRequest Implements FTP protocol for file operations

Conclusion

The System.Net namespace in C# provides comprehensive networking capabilities including web requests, DNS operations, and FTP transfers. It automatically handles SSL encryption for secure connections and offers easy-to-use classes for common networking tasks.

Updated on: 2026-03-17T07:04:35+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements