2011-09-02 3 views
1

원격 URL에서 실제 파일 확장자를 가져오고 싶습니다.원격 URL에서 유효한 파일 이름 및 확장자를 저장하는 방법.

가끔 확장자가 유효한 형식이 아닙니다.

예를
위해 나는

방법은 위의 URL에서 파일 이름과 확장자를 얻으려면 ... URL을

내가/다운로드 원격 URL에서 원격 이미지를 저장할
1) http://tctechcrunch2011.files.wordpress.com/2011/09/media-upload.png?w=266 
2) http://0.gravatar.com/avatar/a5a5ed70fa7c651aa5ec9ca8de57a4b8?s=60&d=identicon&r=G 

아래에서 문제를 점점?

감사
Abhishek는

답변

6

원격 서버 자원의 MIME 유형을 포함하는 Content-Type 헤더를 전송한다. 예를 들면 다음과 같습니다.

Content-Type: image/png 

따라서이 헤더의 값을 검토하고 파일에 대한 적절한 확장자를 선택할 수 있습니다. 예를 들어 당신이 URL에서 확장을 추출 할 경우

WebRequest request = WebRequest.Create("http://0.gravatar.com/avatar/a5a5ed70fa7c651aa5ec9ca8de57a4b8?s=60&d=identicon&r=G"); 
using (WebResponse response = request.GetResponse()) 
using (Stream stream = response.GetResponseStream()) 
{ 
    string contentType = response.ContentType; 
    // TODO: examine the content type and decide how to name your file 
    string filename = "test.jpg"; 

    // Download the file 
    using (Stream file = File.OpenWrite(filename)) 
    { 
     // Remark: if the file is very big read it in chunks 
     // to avoid loading it into memory 
     byte[] buffer = new byte[response.ContentLength]; 
     stream.Read(buffer, 0, buffer.Length); 
     file.Write(buffer, 0, buffer.Length); 
    } 
} 
+0

웹 요청을 보낼 때 Content-Type을 얻는 방법. –

+0

할 수 없습니다. 결국, 실제로 서버가 전송할 때까지 서버가 귀하에게 보낼 것을 어떻게 예상 할 수 있습니까? 일단 WebResponse가 있으면 해당 content-type을 얻을 수 있습니다. – spender

+0

@Abhishek Bhalani의 Content-Type 헤더는 요청이 아니라 응답에 있습니다. 나는 그 모범을 보여 주었다. –

0

당신은 VirtualPathUtility를 사용할 수 있습니다.

var ext = VirtualPathUtility.GetExtension(pathstring) 

또는 콘텐츠 유형을 결정할 때 헤더를 사용하십시오. 콘텐츠 유형을 확장자 (레지스트리에도 있음)로 변환하는 Windows API가 있지만 웹 앱의 경우 매핑을 사용하는 것이 좋습니다.

switch(response.ContentType) 
{ 
    case "image/jpeg": 
     return ".jpeg"; 
    case "image/png": 
     return ".png"; 
} 
+0

URL : "http : ///0.gravatar.com/avatar/a5a5ed70fa7c651aa5ec9ca8de57a4b8?s=60&d=identicon&r=G"그러면 예외가 발생합니다 .. –

+0

예, 'Path'와 같은 방식으로 문자열을 사용합니다. 파일 시스템 경로. 확장 기능이 없으면 작동하지 않을 것이므로 컨텐츠 유형 접근 방식이 필요합니다. – TheCodeKing

+0

@CodeKing thanks –

관련 문제