Search code examples
c#authenticationwindows-8.1windows-store

Windows 8.1 store app Download file using authentication and header


I'm trying to download a file from a server and adding authentication and range header in my app, so is this syntax correct?

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(address);
                        request.Headers["Range"] = "bytes=0-";
                        request.Credentials = new NetworkCredential("username","password");

Of course the code has other parts for reading the file as a stream and storing it but i'm concerned with the range header and authentication part because it's not working.

I get an exception

{"The 'Range' header must be modified using the appropriate property or method.\r\nParameter name: name"}

Solution

  • Here is another way to do it

       var httpClientHandler = new HttpClientHandler();
                            httpClientHandler.Credentials = new System.Net.NetworkCredential("username", "password");
                            var client = new HttpClient(httpClientHandler);
                            System.Net.Http.HttpRequestMessage request = new System.Net.Http.HttpRequestMessage(HttpMethod.Post, new Uri(url));
                            request.Headers.Range = new RangeHeaderValue(0, null);
                            HttpResponseMessage response = await client.SendAsync(request);