Reading Files From Given Specific URL Using WebClient

This article is about reading files from a given specific URL using WebClient.

The WebClient Class is for sending data to and receiving data from local, intranet and internet systems.

In my article I've used some methods provided by the WebClient Class.

For more information about the WebClient class click in the link http://msdn.microsoft.com/en-us/library/system.net.webclient%28v=vs.80%29.aspx.

I've used DownloadFile and DownloadData from a given URL; I hope this will be beneficial in the future.

Kindly look into the code given below:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Net;

using System.IO;

using System.Web;

using System.Web.UI;

 

namespace ReadPDFFromURL

{

    class Program

    {

        StreamReader reader = null;

        static WebClient client = null;

        static void Main(string[] args)

        {

            //String variable used to downlaod File from Given URL

            string urlAddress = "http://iica.in/images/Web%20advt.%20for%20Head%20of%20Centre.pdf";

            //String variable used to downlaod data from Given URL,Here i've used path from my local,

            //You can use path from some IP as well

            string strFileUrlToDownload = "http://localhost/PDF/My_Service.txt";

 

            DownloadFile(urlAddress);

            DownloadData(strFileUrlToDownload);

 

        }     

 

        public static void DownloadFile(string urlAddress)

        {          

            client = new WebClient();

            //DownlaodFile method directely downlaod file on you given specific path ,Here i've saved in E: Drive

            client.DownloadFile(urlAddress,@"E:\\DownloadPdf.pdf");                      

           

        }

 

        public static void DownloadData(string strFileUrlToDownload)

        {

            byte[] myDataBuffer = client.DownloadData((new Uri(strFileUrlToDownload)));

 

            MemoryStream storeStream = new MemoryStream();

 

            storeStream.SetLength(myDataBuffer.Length);

            storeStream.Write(myDataBuffer, 0, (int)storeStream.Length);

 

            storeStream.Flush();

 

            //TO save into certain file must exist on Local

            SaveMemoryStream(storeStream, "C:\\TestFile.txt");

 

            //The below Getstring method to get data in raw format and manipulate it as per requirement

            string download = Encoding.ASCII.GetString(myDataBuffer);

 

            Console.WriteLine(download);

            Console.ReadLine();

        }

        public static void SaveMemoryStream(MemoryStream ms, string FileName)

        {

            FileStream outStream = File.OpenWrite(FileName);

            ms.WriteTo(outStream);

            outStream.Flush();

            outStream.Close();

        }

    }

}
 


Similar Articles