Skip to main content

How to use HttpWebRequest in .NET

Internet applications can be classified broadly into two kinds: client applications that request information, and server applications that respond to information requests from clients. The classic Internet client-server application is the World Wide Web, where people use browsers to access documents and other data stored on Web servers worldwide. 

The System.Net.WebClient class provides functionality to upload data to or download data from the Internet or intranet or a local file system. The WebClient class provides many ways to download and upload data. The following table describes WebClient class methods and properties briefly.
Code :
        public class ClsDownloadFile
        {
            // The stream of data retrieved from the web server
            private Stream strResponse;
            // The stream of data that we write to the harddrive
            private Stream strLocal;
            // The request to the web server for file information
            private HttpWebRequest webRequest;
            // The response from the web server containing information about the file
            private HttpWebResponse webResponse;

            public void DownloadFile(object startPoint, string DestinationPath, String SourcePath)
            {
                try
                {
                    // Put the object argument into an int variable
                    int startPointInt = Convert.ToInt32(startPoint);
                    // Create a request to the file we are downloading
                    webRequest = (HttpWebRequest)WebRequest.Create(SourcePath);
                    // Set the starting point of the request
                    webRequest.AddRange(startPointInt);
                    // Set default authentication for retrieving the file
                    webRequest.Credentials = CredentialCache.DefaultCredentials;
                    // Retrieve the response from the server
                    webResponse = (HttpWebResponse)webRequest.GetResponse();
                    // Ask the server for the file size and store it
                    Int64 fileSize = webResponse.ContentLength;
                    // Open the URL for download
                    strResponse = webResponse.GetResponseStream();
                    // Create a new file stream where we will be saving the data (local drive)
                    if (startPointInt == 0)
                    {
                        strLocal = new FileStream(DestinationPath, FileMode.Create, FileAccess.Write, FileShare.None);
                    }
                    else
                    {
                        strLocal = new FileStream(DestinationPath, FileMode.Append, FileAccess.Write, FileShare.None);
                    }
                    // It will store the current number of bytes we retrieved from the server
                    int bytesSize = 0;
                    // A buffer for storing and writing the data retrieved from the server
                    byte[] downBuffer = new byte[2048];
                    // Loop through the buffer until the buffer is empty
                    while ((bytesSize = strResponse.Read(downBuffer, 0, downBuffer.Length)) > 0)
                    {
                        // Write the data from the buffer to the local hard drive
                        strLocal.Write(downBuffer, 0, bytesSize);
                    }
                }
                finally
                {
                    // When the above code has ended, close the streams
                    strResponse.Close();
                    strLocal.Close();
                }
            }
        }


Call Function Using blow code



ClsDownloadFile _ObjDownload = new ClsDownloadFile();

_ObjDownload.DownloadFile("0", @"D:\destination.zip", @"E:\Source.zip");

Comments

Popular posts from this blog

Connected and disconnected architecture in ADO.Net with Example

Connected Architecture of ADO.NET The architecture of ADO.net, in which connection must be opened to access the data retrieved from database is called as connected architecture. Connected architecture was built on the classes connection, command, datareader and transaction.  Connected architecture is when you constantly make trips to the database for any CRUD (Create, Read, Update and Delete) operation you wish to do. This creates more traffic to the database but is normally much faster as you should be doing smaller transactions. Disconnected Architecture in ADO.NET The architecture of ADO.net in which data retrieved from database can be accessed even when connection to database was closed is called as disconnected architecture. Disconnected architecture of ADO.net was built on classes connection, dataadapter, commandbuilder and dataset and dataview. Disconnected architecture is a method of retrieving a recor

HTTPHandler and HTTPModule in ASP.NET

If you want to implement pre-processing logic before a request hits the IIS resources. For instance you would like to apply security mechanism, URL rewriting, filter something in the request, etc. ASP.NET has provided two types of interception HttpModule and HttpHandler .   The web server examines the file name extension of the requested file, and determines which ISAPI extension should handle the request. Then the request is passed to the appropriate ISAPI extension.  For Example When an .aspx page is requested it is passed to ASP.Net page handler. Then Application domain is created and after that different ASP.Net objects like Httpcontext, HttpRequest, HttpResponse. HTTPModule: -    It's just like a filter. The Modules are called before and after the handler executes . -    HTTP Modules are objects which also participate the pipeline but they work before and after the HTTP Handler does its job, and produce additional services within the pipeline -  

ASP.NET Page Life Cycle with example

In this article, we are going to discuss the different methods and order they are executed during the load of an .aspx web page. Methods Description Page_PreInit Before page Initialization Page_Init Page Initialization LoadViewState View State Loading LoadPostData Postback Data Processing Page_Load Page Loading RaisePostDataChangedEvent PostBack Change Notification RaisePostBackEvent PostBack Event Handling Page_PreRender Page Pre Rendering Phase SaveViewState View State Saving Page_Render Page Rendering Page_Unload Page Unloading PreInit : The entry point of the page life cycle is the pre-initialization phase called “PreInit”. You can dynamically set the values of master pages and themes in this event. You can also dynamically create controls in this event.  Init : This event fires after each control h