好的,我们有一个 PHP 脚本,它从文件创建下载链接,我们想通过 C# 下载该文件。这适用于进度等,但是当 PHP 页面出现错误时,程序会下载错误页面并将其保存为请求的文件。这是我们在ATM上的代码:
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);
}