用Xamarin下载文件

时间:2017-09-20 08:21:11

标签: c# android xamarin

我试图用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方法的override var hidesBottomBarWhenPushed: Bool { return true } 中。 我创建了一个文件夹并尝试将文件保存到其中。

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

感谢。

2 个答案:

答案 0 :(得分:2)

您只创建了一个文件夹,但没有为下载文件创建文件,您只需修改代码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"); 

答案 1 :(得分:0)

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();
    // ...
}
相关问题