【问题标题】:Download file with Xamarin使用 Xamarin 下载文件
【发布时间】:2017-09-20 08:21:10
【问题描述】:

我正在尝试使用 Xamarin 下载文件,但收到错误消息:

在 WebClient 请求期间发生异常。我认为问题在于 unhautorization,但我尝试为多个网络下载 imagen,并且遇到了同样的问题。

代码:

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);
} 

错误消息出现在Console.WriteLine(Completed 方法中。 首先我创建一个文件夹并尝试将文件保存到其中。

当这个工作时,只需要从本地服务器下载文件。

谢谢。

【问题讨论】:

标签: c# android xamarin


【解决方案1】:

你只创建了一个文件夹,并没有创建一个文件下载文件,你可以修改你的代码webClient.DownloadFileAsync(new Uri("http://www.dada-data.net/uploads/image/hausmann_abcd.jpg"), folder);例如这样:

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

【讨论】:

    【解决方案2】:
    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();
        // ...
    }
    

    【讨论】:

      猜你喜欢
      • 2020-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多