1

This is related to How to download a file from a URL in C#? but in my case the url dosen't have file name included in url. suppose a url www.test.com/files0 is a file and in the browser it gets downloaded as 123.mpg how can i save it on server with the same name and extention?

Basically, I want to get filename and type before downloading the file from url and only download the file if it is an allowed extension.

Community
  • 1
  • 1
Ratna
  • 2,289
  • 3
  • 26
  • 50
  • 1
    I don't think a server will even allow you to download a file with out the filename / full path to the file. – Austinh100 Apr 27 '15 at 13:53
  • 1
    You should have file name in respons header `Content-Disposition` – py3r3str Apr 27 '15 at 14:09
  • No extension will be an unknown MIME type. If IIS isn't set up to serve this you won't be able to download it... – Tim Apr 27 '15 at 14:14

1 Answers1

4

Assuming that you're using the HttpClient class to make your request, You can use the HttpResponseMessage that your query returns to decide if you want to download the file or not. For example:

HttpClient client = new HttpClient();

HttpResponseMessage response = await client.GetAsync("http://MySite/my/download/path").ConfigureAwait(false);

if (!String.Equals(response.Content.Headers.ContentDisposition.DispositionType, "attachment", StringComparison.OrdinalIgnoreCase)) {
  return;
}

// Call some method that will check if the file extension and/or media type 
// of the file are acceptable.
if (!IsAllowedDownload(response.Content.Headers.ContentDisposition.FileName, response.Content.Headers.ContentType.MediaType)) {
  return;
}

// Call some method that will take a stream containing the response payload 
// and write it somewhere.
WriteResponseStream(await response.Content.ReadAsStreamAsync().ConfigureAwait(false));

Luke Hoffmann
  • 918
  • 8
  • 13
Graham Watts
  • 629
  • 5
  • 14