Checking if an arbitrary (remote) URL is a file attachment, and extracting it if it is? [Answered]
If I'm given an arbitrary URL (I don't have control over it), how can I check if it appears to be a direct link to a file, and if it is, extract the filename + extension? It's been a little while so I don't remember why I stopped using it, but I tried using
Path.GetFileName()
and it didn't work correctly all of the time. IIRC, it would preserve any garbage data like query parameters after the end of the filename, so instead of http://example.com/image.png?width=420&height=69
producing image.png
, it would produce image.png?width=420&height=69
? It's been a hot second so I don't remember if this was the exact problem.7 Replies
After asking this I realize that I could probably just still use
Path.GetFileName()
and then trim everything after the first ?
after the last period? Still, dunno if there are better methods out there, I'm curiousUse a
Uri
to extract the path
Then use Path.GetFileName
after it's been normalizedSo I construct a
Uri
with the url, and then use Path.GetFileName(uri.LocalPath)
? or is it RemotePath?Probably
AbsolutePath
?
For the URI file://computer/file.ext, the absolute path is /file.ext and the local path is \computer\file.ext.Not sure which is the one you want
AbsolutePath works just fine 👍
now to check how it handles, well, a URI not being to a file with an extension
Just in case anyone else needs to know this information:
- if your arbitrary URL ends in
/
, extracting the filename via Path.GetFileName()
will return an empty string
- if your arbitrary URL does not end in /
, extracting the filename will return whatever text was after the last /
but before any query parameters (essentially a fake file with no extension - check for periods, i guess?)✅ This post has been marked as answered!