2014-10-04 58 views
0

在实现了简单下载程序的基本版本之后,我花了几个小时搜索了解如何获取我的URL的类型,如.mp3, .mp4等。诸如日常动作等网站的URL没有在最后附加它。这是因为我的Downloader适用于这些类型,但是没有特定类型的链接会使其下载Kb文件而无法播放。如何从URL中获取数据类型

这里是确定内容类型决定*。扩展名进行下载代码:

 WebClient myWebClient = new WebClient(); 
     string datastring = myWebClient.DownloadString("http://www.dailymotion.com/video/x1viyeu_pakistani-actress-meera-reema-saima-dance-on-faisal-ahmed-music-album-launch_news"); 
     NameValueCollection headers = myWebClient.ResponseHeaders; 
     foreach (string key in headers.AllKeys) 
     { 

      Console.WriteLine("Header:{0},Value:{1}", key, headers[key]); 


     } 

这回我的输出在控制台的名单中具有管线是:

页眉:Content-Type,Value:text/html; charset = utf-8

现在我想听听那将如何帮助我解决已经描述的问题。

建议,请

这里是下载

private void downloadbtn_Click(object sender, EventArgs e) 
    { 

     WebClient myWebClient = new WebClient(); 

     //Declarations for string objects 
     string downloadURL, path; 
     //raw URL taken from user 
     downloadURL = this.downloadURL.Text; 
     path = this.savePath.Text; 


     Uri tmp = new Uri(downloadURL); 
     string EndPathFileName = tmp.Segments.Last(); 
     path = path + @"\" + EndPathFileName; 

     //downloads file using async method 

     myWebClient.DownloadFileAsync(tmp, path); 

     downloadbtn.Text = "Download Started"; 
     downloadbtn.Enabled = false; 

     myWebClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged); 
     myWebClient.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted); 




    } 
+0

你能更具体,我听到etc.but couldn”一样MIME弄清楚。? – 2014-10-04 08:09:37

+0

形象重复是一件相当简单的工作:-) – 2014-10-09 07:31:27

+0

这是之前问过,但现在文本/ HTML有更多的事要做 – 2014-10-09 07:32:13

回答

0

通常有一种Content-Type头,可以给你的期望是什么文件类型提示的代码。

很多时候,服务器还会提供关于文件名的信息 - 关于如何通常在(PHP)服务器端完成,请参阅this SO

+0

如果你指的是这样的事情:NameValueCollection headers = myWebClient.ResponseHeaders; 的foreach(在headers.AllKeys字符串键) { Console.WriteLine( “部首:{0},值:{1}”,键,标头[键]); } – 2014-10-04 08:20:54

+0

但是它返回NullReference异常 – 2014-10-04 08:21:44

+0

哪一行产生异常? – mbanzon 2014-10-04 08:23:41

0

根据本 http://www.w3.org/Protocols/rfc2616/rfc2616-sec7.html#sec7.2.1

Any HTTP/1.1 message containing an entity-body SHOULD include a Content-Type header field defining the media type of that body. 
+0

有没有可能,一个网站没有返回回应..我经验为一个这样的网站 – 2014-10-04 10:05:50

0

你可以得到一个内容类型和拆分它想:

var request = HttpWebRequest.Create("http://www.google.com") as HttpWebRequest; 
     if (request != null) 
     { 
      var response = request.GetResponse() as HttpWebResponse; 

      string contentType = ""; 

      if (response != null) 
       contentType = response.ContentType; 
      int start = contentType.IndexOf('/'); 
      int end = contentType.IndexOf(';', start); 
      string yourext = contentType.Substring(start+1, (end - start)-1);//like mp3,png,txt 
     } 
+0

是否WebClient支持这样的方法,因为我在整个项目中使用 – 2014-10-04 08:23:07

+0

用下载代码更新您的问题! – Yehia 2014-10-04 08:25:12

+0

已更新@Yehiya – 2014-10-04 09:56:12