I'm currently programming a download manager, which has a function of adding links from clipboard.
Now I need to write a method to find out the filename of the file which is in the link, e.g. a method which outputs the filename: "https://example.com/document.doc" outputs "document.doc" "https://example.com/document.doc?smth=123" outputs "document.doc" "https://exmaple.com/download?file=123" outputs the filename of the file behind this link
I tried, but i only works for the first link:
string[] uriparts = i.Split('/');
string filename = uriparts[uriparts.Length - 1];
You can use
Uriclass to work with an URLs, it will extract separate parts like host, protocol, path, query string, etc. Then you can usePathclass to deal with path and extract filename from it:However
In most cases you cannot get the filename by just looking at the URL. And even if URL looks like it includes actual filename (e.g.
https://example.com/download/document.doc) you can't guarantee that when you follow this URL, you'll download thedocument.docfile.The actual file name is returned in the
Content-Dispositionheader of the response when you navigate the URL.So you can try to get it from the URL initially, but you should be ready that it might not include filename at all, and that server could return you different filename when you execute the request.
And, as a fallback, you might need to generate your own filename (in case server doesn't return one). For example (here I'm using
MimeTypesnuget package to map MediaType into file extension when generating file name):