Downloading a file from a PHP page in C#
Posted
by
FoxyShadoww
on Stack Overflow
See other posts from Stack Overflow
or by FoxyShadoww
Published on 2012-11-14T22:53:13Z
Indexed on
2012/11/14
23:00 UTC
Read the original article
Hit count: 280
Okay, we have a PHP script that creates an download link from a file and we want to download that file via C#. This works fine with progress etc but when the PHP page gives an error the program downloads the error page and saves it as the requested file. Here is the code we have atm:
PHP Code:
<?php
$path = 'upload/test.rar';
if (file_exists($path)) {
$mm_type="application/octet-stream";
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Type: " . $mm_type);
header("Content-Length: " .(string)(filesize($path)) );
header('Content-Disposition: attachment; filename="'.basename($path).'"');
header("Content-Transfer-Encoding: binary\n");
readfile($path);
exit();
}
else {
print 'Sorry, we could not find requested download file.';
}
?>
C# Code:
private void btnDownload_Click(object sender, EventArgs e)
{
string url = "http://***.com/download.php";
WebClient client = new WebClient();
client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
client.DownloadFileAsync(new Uri(url), @"c:\temp\test.rar");
}
private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
progressBar.Value = e.ProgressPercentage;
}
void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
MessageBox.Show(print);
}
© Stack Overflow or respective owner