C#从PHP网页下载文件



在服务器上,我有一个php文件可以根据请求提供文件,它可以在web浏览器中正常工作,并下载所需的文件。现在我需要使用WebRequest从c#应用程序下载该文件,但它只保存了一个空文件。

这是php服务器端:

<?php
$file = basename($_POST['File']);
$file = '../Uploads/' . $file;
if(!file_exists($file)){ // file does not exist
die('file not found');
} else {
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file");
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: binary");
// read the file from disk
readfile($file);
}
?>

在C#应用程序中,我使用以下代码:

public void DownloadFileAsync(string file)
{
ct = new CancellationTokenSource();
Task.Factory.StartNew(() =>
{
try
{
WebRequest request = WebRequest.Create(serverURL);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
byte[] buffer;
buffer = Encoding.ASCII.GetBytes("File=" + file);
request.ContentLength = buffer.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(buffer, 0, buffer.Length);
//get response
using (WebResponse response = request.GetResponse())
using (Stream responseStream = response.GetResponseStream())
{
using (FileStream fileStream = File.Create(Path.Combine(sharedFolder, values["File"])))
{
responseStream.CopyTo(fileStream);
}
}                }
catch (Exception ex)
{
//
}
}, ct.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
}

它运行良好,我刚刚发现我在服务器url 中传递了错误的url

最新更新