vb.net 有没有办法从 URL 获取文件扩展名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23228378/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there any way to get the file extension from a URL
提问by z3nth10n
I want to know that for make sure that the file that will be download from my script will have the extension I want.
我想知道,以确保将从我的脚本下载的文件具有我想要的扩展名。
The file will not be at URLs like:
该文件不会位于以下 URL 处:
http://example.com/this_url_will_download_a_file
Or maybe yes, but, I think that I will only use that kind of URL:
或者也许是的,但是,我认为我只会使用这种 URL:
http://example.com/file.jpg
I will not check it with: Url.Substring(Url.LastIndexOf(".") - 3, 3)because this is a very poor way.
我不会检查它:Url.Substring(Url.LastIndexOf(".") - 3, 3)因为这是一种非常糟糕的方式。
So, what do you recommend me to do?
那么,你建议我做什么?
回答by heringer
It is weird, but it works:
这很奇怪,但它有效:
string url = @"http://example.com/file.jpg";
string ext = System.IO.Path.GetExtension(url);
MessageBox.Show(this, ext);
but as crono remarked bellow, it will not work with parameters:
但正如 crono 在下面评论的那样,它不适用于参数:
string url = @"http://example.com/file.jpg?par=x";
string ext = System.IO.Path.GetExtension(url);
MessageBox.Show(this, ext);
result: ".jpg?par=x"
结果:“.jpg?par=x”
回答by Alex
here's a simple one I use. Works with parameters, with absolute and relative URLs, etc. etc.
这是我使用的一个简单的。使用参数、绝对和相对 URL 等。
public static string GetFileExtensionFromUrl(string url)
{
url = url.Split('?')[0];
url = url.Split('/').Last();
return url.Contains('.') ? url.Substring(url.LastIndexOf('.')) : "";
}
Unit test if you will
单元测试,如果你愿意
[TestMethod]
public void TestGetExt()
{
Assert.IsTrue(Helpers.GetFileExtensionFromUrl("../wtf.js?x=wtf")==".js");
Assert.IsTrue(Helpers.GetFileExtensionFromUrl("wtf.js")==".js");
Assert.IsTrue(Helpers.GetFileExtensionFromUrl("http://www.com/wtf.js?wtf")==".js");
Assert.IsTrue(Helpers.GetFileExtensionFromUrl("wtf") == "");
Assert.IsTrue(Helpers.GetFileExtensionFromUrl("") == "");
}
Tune for your own needs.
根据您自己的需要进行调整。
P.S. Do notuse Path.GetExtensioncause it does not work with query-string params
PS 不要使用Path.GetExtension因为它不适用于查询字符串参数
回答by SteeBono
I know that this is an old question, but can be helpful to people that see this question.
我知道这是一个老问题,但对看到这个问题的人可能会有所帮助。
The best approach for getting an extension from filename inside an URL, also with parameters are with regex.
从 URL 中的文件名获取扩展名的最佳方法也是使用正则表达式。
You can use this pattern (not urls only):
您可以使用此模式(不仅仅是网址):
.+(\.\w{3})\?*.*
Explanation:
解释:
.+ Match any character between one and infinite
(...) With this, you create a group, after you can use for getting string inside the brackets
\. Match the character '.'
\w Matches any word character equal to [a-zA-Z0-9_]
\?* Match the character '?' between zero and infinite
.* Match any character between zero and infinite
Example:
例子:
http://example.com/file.png
http://example.com/file.png?foo=10
But if you have an URL like this:
http://example.com/asd
This take '.com' as extension.
So you can use a strong pattern for urls like this:
因此,您可以对这样的 url 使用强模式:
.+\/{2}.+\/{1}.+(\.\w+)\?*.*
Explanation:
解释:
.+ Match any character between one and infinite
\/{2} Match two '/' characters
.+ Match any character between one and infinite
\/{1} Match one '/' character
.+ Match any character between one and infinite
(\.\w+) Group and match '.' character and any word character equal to [a-zA-Z0-9_] from one to infinite
\?* Match the character '?' between zero and infinite
.* Match any character between zero and infinite
Example:
例子:
http://example.com/file.png (Match .png)
https://example.com/file.png?foo=10 (Match .png)
http://example.com/asd (No match)
C:\Foo\file.png (No match, only urls!)
http://example.com/file.png
http: .+
// \/{2}
example.com .+
/ \/{1}
file .+
.png (\.\w+)
回答by Justin
If you just want to get the .jpgpart of http://example.com/file.jpgthen just use Path.GetExtensionas heringersuggests.
如果您只是想获得其中的.jpg一部分,http://example.com/file.jpg那么只需Path.GetExtension按照heringer 的建议使用即可。
// The following evaluates to ".jpg"
Path.GetExtension("http://example.com/file.jpg")
If the download link is something like http://example.com/this_url_will_download_a_filethen the filename will be contained as part of the Content-Disposition, a HTTP header that is used to suggest a filename for browsers that display a "save file" dialog. If you want to get this filename then you can use the technique suggested by Get filename without Content-Dispositionto initiate the download and get the HTTP headers, but cancel the download without actually downloading any of the file
如果下载链接类似于,http://example.com/this_url_will_download_a_file那么文件名将作为Content-Disposition 的一部分包含在内,这是一个 HTTP 标头,用于为显示“保存文件”对话框的浏览器建议文件名。如果您想获取此文件名,则可以使用Get filename without Content-Disposition建议的技术来启动下载并获取 HTTP 标头,但取消下载而不实际下载任何文件
HttpWebResponse res = (HttpWebResponse)request.GetResponse();
using (Stream rstream = res.GetResponseStream())
{
string fileName = res.Headers["Content-Disposition"] != null ?
res.Headers["Content-Disposition"].Replace("attachment; filename=", "").Replace("\"", "") :
res.Headers["Location"] != null ? Path.GetFileName(res.Headers["Location"]) :
Path.GetFileName(url).Contains('?') || Path.GetFileName(url).Contains('=') ?
Path.GetFileName(res.ResponseUri.ToString()) : defaultFileName;
}
res.Close();
回答by Cedric Arnould
Here is my solution:
这是我的解决方案:
if (Uri.TryCreate(url, UriKind.Absolute, out var uri)){
Console.WriteLine(Path.GetExtension(uri.LocalPath));
}
First, I verify that my url is a valid url, then I get the file extension from the local path.
首先,我验证我的 url 是一个有效的 url,然后我从本地路径获取文件扩展名。
回答by Sean T
Some have suggested requesting the file from the url and checking the headers. That's overkill for something so simple in my opinion so...
有些人建议从 url 请求文件并检查标题。在我看来,这对于如此简单的事情来说太过分了,所以......
Heringers answer fails if parameters are present on the url, the solution is simple just Spliton the query string char ?.
如果 url 上存在参数,Heringers 回答失败,解决方案很简单,仅Split在查询字符串 char 上?。
string url = @"http://example.com/file.jpg";
string ext = System.IO.Path.GetExtension(url.Split('?')[0]);
回答by roxl
VirtualPathUtility.GetExtension(yourPath); Returns the file extension from the specified path, including the leading period.
VirtualPathUtility.GetExtension(yourPath); 返回指定路径的文件扩展名,包括前导句点。

