WP8 - WebBrowser class : How to handle downloading of file?
I have created a simple app in WP8 to display web pages using the Microsoft.Phone.Controls.WebBrowser class. I am able to load the page, navigate links, move back and forward in history. Apart from this basic functionality I also want to provide means to download files which cannot be displayed within the browser like say .ppt or .mp3.
I have not been able to find anything in the WebBrowser class documentation to initiate a download. There is just a Navigate function which takes a URL to load.
So can a download be done using WebBrowser class?
Or is there any way to automatically invoke the system viewer for the file (like powerpoint for ppt) which has been downloaded?
Re: WP8 - WebBrowser class : How to handle downloading of file?
No WebBrowser can't download file but here are two classes that can do it :
You can use [URL="http://msdn.microsoft.com/fr-fr/library/system.net.webclient(v=vs.95).aspx"]WebClient[/URL] or [URL="http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest(v=vs.95).aspx"]HttpWebRequest[/URL]
[code]WebClient client = new WebClient();
client.OpenReadCompleted += new OpenReadCompletedEventHandler(YourMethodToGetTheFile_OpenReadCompleted);
[code]var uri = new Uri("http://www.WebSite.com/TheFile.ppt");
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.BeginGetResponse(new AsyncCallback(YourMethodToGetTheFile_AsyncCallBack), request);[/code]
You can use one of the snippets above and then simply store the stream you get as a response in the [B]IsolatedStorageFile[/B]
something like this for the WebClient
[code]void YourMethodToGetTheFile_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
var storeFile = IsolatedStorageFile.GetUserStoreForApplication();
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream("TheFile.ppt", System.IO.FileMode.Create, storeFile ))
byte buffer = new byte;
while (e.Result.Read(buffer, 0, buffer.Length) > 0)
stream.Write(buffer, 0, buffer.Length);
Don't forget to delete the file if exist in the IsolatedStorage, I didn't handle it in the example.