NetworkCredential

In this chapter you will learn:

  1. How to use NetworkCredential to do Web login
  2. Login FTP with Authentication

Web login

using System;//from  ja v a 2s.  co  m
using System.Net;
using System.Text;

class MainClass
{
   public static void Main()
   {
      WebClient wc = new WebClient();

      NetworkCredential nc = new NetworkCredential("usr", "mypassword");

      wc.Credentials = nc;

      byte[] response = wc.DownloadData("http://localhost/testlogin");
      Console.WriteLine(Encoding.ASCII.GetString(response));
   }
}

FTP Authentication

You can supply a username and password to an HTTP or FTP site by creating a NetworkCredential object and assigning it to the Credentials property of WebClient or WebRequest:

using System;//from ja v  a 2  s.c  o  m
using System.Net;
using System.IO;
using System.Linq;
using System.Text;

class Program
{
    static void Main()
    {
        WebClient wc = new WebClient();
        wc.Proxy = null;
        wc.BaseAddress = "ftp://ftp.abc.com";

        // Authenticate, then upload and download a file to the FTP server.
        // The same approach also works for HTTP and HTTPS.

        string username = "nutshell";
        string password = "yourValue";
        wc.Credentials = new NetworkCredential(username, password);

        wc.DownloadFile("guestbook.txt", "guestbook.txt");

        string data = "Hello from " + Environment.UserName + "!\r\n"; 
        File.AppendAllText("guestbook.txt", data);

        wc.UploadFile("guestbook.txt", "guestbook.txt");
    }
}

Next chapter...

What you will learn in the next chapter:

  1. How to ping a IP address to see if it is alive
Home » C# Tutorial » Network
Cookie
CredentialCache
HostEntry
IPHostEntry
IP address from host name
IPEndPoint from IPAddress
IPEndPoint Port
IPEndPoint properties
IPHostEntry
IP Address Parser
Predefined IP Address
NetworkCredential
Ping
Udp Client
Socket connection
Socket creation
Socket sendTo
TcpClient
TcpListener
UdpClient Receive
UdpClient Sending
Uri
WebClient
Response Headers
WebProxy
WebRequest