How to Connect and Download a file from a RESTFUL service

Posted by | Posted in Web, Winform, Mobile, WinPhone, WPF, WCF, Azure | Posted on 09-05-2012

The FileDownloadResponse object was just part of my implementation of the Request/Response pattern.
Most apps run within secure networks hidden behind proxies; ensure you specify a username and password.
Good practice would be to create a new user with sufficent rights for this task.

        public FileDownloadResponse DownloadFrom(FileDownloadRequest request)
        {
            FileDownloadResponse response = new FileDownloadResponse();

            try
            {
                using (WebClient webclient = new WebClient())
                {
                    IWebProxy proxy = webclient.Proxy;

                    proxy.Credentials = CredentialCache.DefaultCredentials;
                    webclient.Proxy = proxy;
                    webclient.Credentials = new NetworkCredential(username, password);
                    webclient.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);

                    //this is where the downloading occurs. Use a stop watch around this to log the time taken for process to complete.
                    webclient.DownloadFile(request.RequestUri, Path.Combine(request.FileDownloadLocation, request.FileName));
                  
                    
                    response.DurationMSecs = Convert.ToDouble(stopWatch.ElapsedMilliseconds);
                    response.DownloadState = DownloadStateEnum.Complete;
                }

                return response;
            }
            catch (WebException webException)
            {
                //Rethrowing the error
                throw;
            }
        }
    }

Read More

Comments are closed.