[Windows 8] How to download files from FTP ?
August 17th, 2012 | Posted by in .NET | Article | Windows 8 | WinJS | WinRT | Read: 1,907Downloading files is a common scenario, specially in connected apps like you can find in Windows 8.
When these files are hosted in Web server, downloads is really easy to perform using a WebRequest (C#) or XHR (XmlHttpRequest, in JS). But when the files are located on FTP server, it’s a bit more complicated so we have to find a way to be able to download files.
The answer to this problem is to use the BackgroundDownloader class:
var file = await KnownFolders.DocumentsLibrary.CreateFileAsync("Yoda.jpg", CreationCollisionOption.ReplaceExisting); var pc = new PasswordCredential(); pc.UserName = "freebox"; pc.Password = "XXXXX"; var downloader = new BackgroundDownloader(); downloader.ServerCredential = pc; var downloadOperation = downloader.CreateDownload(new Uri("ftp://hd1.freebox.fr/Disque dur/Yoda.jpg"), file); var progressCallback = new Progress<DownloadOperation>(op => { if (op.Progress.TotalBytesToReceive > 0) { Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { this._progressPercent = op.Progress.BytesReceived * 100 / op.Progress.TotalBytesToReceive; }); } }); await downloadOperation.StartAsync().AsTask(progressCallback); var response = downloadOperation.GetResponseInformation();
Unfortunately, if you try to execute the following code, you’ll encounter this error:
Indeed, there is actually a bug when you try to specify the ServerCredential property of the BackgroundDownloader (thanks to Katrien De Graeve, @katriendg for pointing me this). The workaround is to set the username/password in the Uri:
var file = await KnownFolders.DocumentsLibrary.CreateFileAsync("Yoda.jpg", CreationCollisionOption.ReplaceExisting); var pc = new PasswordCredential(); pc.UserName = "freebox"; pc.Password = "XXXXX"; var downloader = new BackgroundDownloader(); //downloader.ServerCredential = pc; var downloadOperation = downloader.CreateDownload(new Uri("ftp://freebox:XXXXX@hd1.freebox.fr/Disque dur/Yoda.jpg"), file); var progressCallback = new Progress<DownloadOperation>(op => { if (op.Progress.TotalBytesToReceive > 0) { Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { this._progressPercent = op.Progress.BytesReceived * 100 / op.Progress.TotalBytesToReceive; }); } }); await downloadOperation.StartAsync().AsTask(progressCallback); var response = downloadOperation.GetResponseInformation();
Using this code, you’ll be able to download the file successfully !
Note that, to use this code, you need to set the following capacities:
Happy coding!
You can follow any responses to this entry through the RSS 2.0 You can leave a response, or trackback.





Pingback: Windows 8 Developer Links – 2012-08-20Dan Rigby | Dan Rigby