C
C#3y ago
Kiel

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
Kiel
KielOP3y ago
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 curious
333fred
333fred3y ago
Use a Uri to extract the path Then use Path.GetFileName after it's been normalized
Kiel
KielOP3y ago
So I construct a Uri with the url, and then use Path.GetFileName(uri.LocalPath)? or is it RemotePath?
333fred
333fred3y ago
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
Kiel
KielOP3y ago
AbsolutePath works just fine 👍
Kiel
KielOP3y ago
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?)
Accord
Accord3y ago
✅ This post has been marked as answered!

Did you find this page helpful?