好的,我们有一个PHP脚本,可以从文件创建下载链接,我们想通过C#下载该文件。这与进度等工作正常但是当PHP页面出错时,程序会下载错误页面并将其保存为请求的文件。以下是我们的代码:
PHP代码:
<?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#代码:
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);
}
答案 0 :(得分:1)
您应该使用PHP记录的here中的Header
函数,而不是打印错误消息。
header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found", true, 404);
由于您的异步调用的性质,不会抛出WebException
。在您的DownloadFileCompleted回调中,您可以检查
if(e.Error != null)
您的e.Error将包含类似于"The remote server returned an error: (404) Not Found."
的行。
答案 1 :(得分:1)
您需要通过设置标头通知webclient发生错误,就像您成功下载时一样。我不熟悉PHP,但发现了一个401示例
header('HTTP/1.0 401 Unauthorized', true, 401);
来自here