Massimo Ausiello
Massimo Ausiello

Reputation: 35

How can I download file in xamarin with webview?

I'm new in a Xamarin development. I hope that you can resolve my problem in a simple mode. I've a crossplatform app developed with Xamarin and I want to download a file from a url.

I tried to download file using C# code but i can't do it (for crossplatform app) so I want to try other way. I want to use a webview and download the file directly into the web view. the problem is that when i click the button "download" into the webview it do anything. can you help me in a simply way?

my webview is this:

<WebView Source="https://download.cnet.com/Free-YouTube-Downloader/3001-2071_4-75219434.html/" x:Name="webv" WidthRequest="1000" HeightRequest="1000" />

it is an example of url

Upvotes: 1

Views: 4147

Answers (1)

Mr Hery
Mr Hery

Reputation: 870

You have some plenty choices. But here's 2 of them. It's a simple one.

  1. Using Device.OpenUri(new Uri("Download link here")). This method is simple. It open the URL in client mobile web browser. And from there, the web browser will handle the background worker for download progress.

  2. Using WebClient() class. Using this class, you'll can have your response in data type that you like maybe string or byte[]. Below's the sample:

var wb = new WebClient();

//Download as string
string x = wb.DownloadString("Download url");

//Download as byte[]
byte[] x = wb.DownloadData("Download Url");

From the return value of x, now you can rewrite it using System.IO to another file.

Note: These method is just basic. You can implement it in task, so your app will not hanging up while the download is in process.

Better approach: Via dependency service, download file from the native Android & iOS itself via interface class. you can check this one out: https://github.com/SimonSimCity/Xamarin-CrossDownloadManager#where-are-the-files-stored

Upvotes: 1

Related Questions