pypypu
pypypu

Reputation: 155

Download file with Xamarin

I'm trying to download file with Xamarin, but receive an error massage:

An exception occurred during a WebClient request. I thing that the problem is with unhautorization, but I try to download imagen for multiple web, and have the same problem.

Code:

public void getFile() {

    var pathToNewFolder = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/CodeScanner";
    Directory.CreateDirectory(pathToNewFolder);

    try
    {                
        WebClient webClient = new WebClient();
        webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);               
        var folder = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/CodeScanner";
        webClient.DownloadFileAsync(new Uri("http://www.dada-data.net/uploads/image/hausmann_abcd.jpg"), folder);
    }
    catch (Exception ex)
    {
        Console.WriteLine("ERROR:"+ ex.Message);
    }            
}


private void Completed(object sender, AsyncCompletedEventArgs e)
{
    Console.WriteLine("ERROR: "+ e.Error.Message);
} 

The error massage appears in Console.WriteLine( of Completed method. Firts I create a folder and try to save file into it.

When this work, only need downloat file from local server.

thanks.

Upvotes: 3

Views: 11113

Answers (2)

Artūras Paleičikas
Artūras Paleičikas

Reputation: 629

var httpClientHandler = new HttpClientHandler
{
    AllowAutoRedirect = false,
    ....
};

var httpClient = new System.Net.Http.HttpClient(httpClientHandler)
{
    MaxResponseContentBufferSize = 5000000,
    ...
};

var uri = new Uri("http://x.com");
using (var response = await httpClient.GetAsync(uri))
{
  if (!response.IsSuccessStatusCode)
       throw new HttpRequestException($"URL {uri} not loaded. {response.StatusCode}");

    var str = await response.Content.ReadAsStringAsync();
    // ...
}

Upvotes: 1

Grace Feng
Grace Feng

Reputation: 16652

You only created a folder, but didn't create a file for download file, you can just modify your code webClient.DownloadFileAsync(new Uri("http://www.dada-data.net/uploads/image/hausmann_abcd.jpg"), folder); for example like this:

webClient.DownloadFileAsync(new Uri("http://www.dada-data.net/uploads/image/hausmann_abcd.jpg"), folder + "/abc.jpg"); 

Upvotes: 2

Related Questions