1

How can I detect if the target link will trigger download, before user actually clicks it?

For example, the following link is a file:

string url="http://www.orimi.com/pdf-test.pdf"

But this one is not:

string url="https://www.google.com/"

I tried like:

Uri uri = new Uri(url);
if (uri.IsFile)
   //...

but it's gives false for the pdf link

spez
  • 409
  • 8
  • 21
  • 6
    You could do a HTTP HEAD request and look at the application type I guess? For this URL it returns "application/pdf" – Ryan Thomas Mar 11 '20 at 09:39
  • 1
    I'd stick with Ryan's suggestion. Check this answer: https://stackoverflow.com/a/5953264/2679160 – roemel Mar 11 '20 at 09:40
  • 1
    To add, the Uri class could be a local file, could be a web address etc. IsFile will only return true for local files, it doesn't know if a web address has a downloadable file. https://learn.microsoft.com/en-us/dotnet/api/system.uri.isfile?view=netframework-4.8 - also if a file is not downloadable it will not have an application type. – Ryan Thomas Mar 11 '20 at 09:42

1 Answers1

4

You can't really know that the link you have doesn't cause a file download (before you call the URL) because even a URL without a file extension can be linked to a file.

What you can do is check if the URL contains a file extension, and this can be done using the following code:

 var uri = new Uri('https://www.google.com/');

 var fileInfo = new FileInfo(uri.AbsolutePath);
  if (!string.IsNullOrWhiteSpace(fileInfo.Extension))
  {
    //Uri has no file extension
  } 
Shai Aharoni
  • 1,955
  • 13
  • 25