Abhishek Kumar Ravi

Abhishek Kumar Ravi

  • NA
  • 11.5k
  • 4.5m

How to Download a file (pdf or ppt) asynchronously in C#

Feb 17 2014 5:43 PM
Actually, i want to put this in Windows Phone.
Since, i have a link (http://xxxx.com/xxxx/abc.pdf) and, i want to download in my Isolated Storage.
 
// My Code
  private void cancleButton_Loaded(object sender, RoutedEventArgs e)
{
// Get The URI from Previous Page
if (NavigationContext.QueryString.ContainsKey("file"))
{
downloadFile = NavigationContext.QueryString["file"];

try
{
wc = new System.Net.WebClient();
// This Statement is for IMAGE Download
wc.OpenReadCompleted += new System.Net.OpenReadCompletedEventHandler(wc_OpenReadCompleted);
wc.OpenReadAsync(new Uri(downloadFile));


downloadStatus.Text = "Downloading Source from " + downloadFile;
downloadResult.Text = string.Empty;
}
catch (Exception ex)
{
MessageBox.Show("Connection Error : " + ex.Message);
}

}

}
 
void wc_OpenReadCompleted(object sender, System.Net.OpenReadCompletedEventArgs e)
{
try
{
// Read File from Server

var file = IsolatedStorageFile.GetUserStoreForApplication();
//downloadFile.Substring(downloadFile.Length,downloadFile.LastIndexOf("/")+1)
 
// First Argument is FILE NAME
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(downloadFile.Substring(downloadFile.Length - (downloadFile.Length - downloadFile.LastIndexOf("/") - 1)), FileMode.Create, file))
{
byte[] buffer = new byte[int.Parse(progressBar.Maximum.ToString())];

while (e.Result.Read(buffer, 0, buffer.Length) > 0)
{
stream.Write(buffer, 0, buffer.Length);
}

MessageBox.Show("You File " + downloadFile.Substring(downloadFile.Length - (downloadFile.Length - downloadFile.LastIndexOf("/") - 1)) + " Downloaded Successfully.", "Successfully !!", MessageBoxButton.OK);
}
}

catch
{

}



 
 
void wc_DownloadProgressChanged(object sender, System.Net.DownloadProgressChangedEventArgs e)
{
// Progress Changed

progressBar.Value = e.BytesReceived;
progressBar.Maximum = e.TotalBytesToReceive;
downloadResult.Text = "Downloaded " + (e.BytesReceived / 1048576) + " MB / " + (e.TotalBytesToReceive / 1048576) + " MB. [ " + e.ProgressPercentage.ToString() + " % ].";