Kritz
Kritz

Reputation: 7331

Download a file from C# after posting valid data

I want users of my c# application to be able to download a file from my website if they provide certain details.

I can download the file using in c# using:

WebClient webClient = new WebClient();
webClient.DownloadFile("http://www.example.com/download.php", "file.txt");

And I can upload values using webClient.UploadValues method, but I don't know how to combine them. That is, to download the file and posting data at the same time.

The download.php file contains the following:

$file = 'file.png';
if ((file_exists($file)) and ($_POST["ID"] == 'abc') ) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
    readfile($file);
    exit;
}
else
header('HTTP/1.0 404 Not Found');
}
?>

How should I post the data from C# and then download the file?

Upvotes: 2

Views: 2009

Answers (1)

KV Prajapati
KV Prajapati

Reputation: 94653

You have to set Content-Type and also pass data.

 WebClient client = new WebClient();
 client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
 byte []result=client.UploadData("http://www.example.com/download.php",
                                 "POST",
                                  System.Text.Encoding.UTF8.GetBytes("ID=abc"));
 //save the byte array `result` into disk file.

Upvotes: 3

Related Questions