Reputation: 4088
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);
}
Upvotes: 0
Views: 2768
Reputation: 7773
Instead of printing an error message, you should use the Header
function in PHP documented here.
header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found", true, 404);
Due to the nature of your Async call, no WebException
is thrown. On your DownloadFileCompleted callback, you can check
if(e.Error != null)
Your e.Error will contain a line similar to "The remote server returned an error: (404) Not Found."
.
Upvotes: 1
Reputation: 2322
You need to inform the webclient that an error as occurred by setting headers just like you have when a successful download is happening. I'm not very familiar with PHP, but found a 401 example
header('HTTP/1.0 401 Unauthorized', true, 401);
from here
Upvotes: 1