2014-04-22 4 views
10

내 스크립트에서 다운로드 할 파일의 확장자가 원하는지 확인하고 싶습니다.URL에서 파일 확장자를 가져 오는 방법이 있습니까

파일과 같은 URL을에되지 않습니다 : 어쩌면 예

http://example.com/this_url_will_download_a_file 

또는하지만, 나는 단지 URL의 종류를 사용하는 것이라고 생각 :

http://example.com/file.jpg 

나는 그것을 확인하지 않습니다 with : Url.Substring(Url.LastIndexOf(".") - 3, 3) 이것은 매우 좋지 않은 방식이기 때문에.

그럼 내가 무엇을 권하고 싶습니까?

+0

당신의 마지막 위치를 얻으려고 수 있을까?. 발견되면,의 마지막 위치를 찾으십시오. 그 사이에 모든 것을 반환합니다. 없다면? 마지막 위치 이후에 오는 것은 무엇이든간에 발견된다. 파일 확장자가됩니다. – Crono

+0

하위 문자열이 작동해야합니다. 길이가 3보다 큰 확장을 고려해야합니다. – Neolisk

+0

은 URL을 제공하는 것입니까? 그들은 자신의 사이트 또는 타사 사이트에 있습니까? –

답변

6

그것은 이상한,하지만 작동합니다

string url = @"http://example.com/file.jpg"; 
string ext = System.IO.Path.GetExtension(url); 
MessageBox.Show(this, ext); 

하지만 crono가 울부 짖는 소리 언급, 그것은 매개 변수와 함께 작동하지 않습니다

string url = @"http://example.com/file.jpg?par=x"; 
string ext = System.IO.Path.GetExtension(url); 
MessageBox.Show(this, ext); 

결과를 : ".JPG를 = X 파"

+0

매개 변수가있는 쿼리에서는 작동하지 않습니다. – Crono

+0

예, 크로노가 맞습니다. 나는 그것을 보지 못했습니다 :) – heringer

3

.jpg 부분을 http://example.com/file.jpg으로 설정하려면 Path.GetExtensionheringer으로 지정하면됩니다.

// The following evaluates to ".jpg" 
Path.GetExtension("http://example.com/file.jpg") 

다운로드 링크는 "파일을 저장"대화 상자를 표시 한 후 파일 이름이 Content-Disposition의 일부 브라우저에서 파일 이름을 제안하는 데 사용되는 HTTP 헤더로 포함됩니다 http://example.com/this_url_will_download_a_file 같은 인 경우. 이 파일 이름을 얻고 싶은 경우에 당신은 다운로드를 시작하기 위해 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(); 
0

나는 이것이 인 것을 알고있는 파일 중 하나를 다운로드하지 않고 다운로드를 취소 할 수 있습니다 오래된 질문이지만이 질문을 보는 사람들에게 도움이 될 수 있습니다.

url 내에서 파일 이름의 확장자를 가져 오는 가장 좋은 방법은 매개 변수와 함께 정규식을 사용하는 것입니다.

당신은이 패턴 (하지 URL을 전용) 사용할 수 있습니다

.+(\.\w{3})\?*.* 

설명 :

.+  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 

예 :

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. 

그래서 당신이 같은 URL에 대한 강한 패턴을 사용할 수 있습니다 this :

.+\/{2}.+\/{1}.+(\.\w+)\?*.* 

설명 :

.+  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 

예 :

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+) 

안녕

관련 문제