如何从URL获取数据类型

时间:2014-10-04 08:03:48

标签: c#

在实施简单下载程序的基本版本后,我花了几个小时用谷歌搜索知道如何获取我的网址类型 .mp3, .mp4等对于日常运动等网站其他人的网址不会在最后附加。这是因为我的下载程序适用于这些类型但是没有特定类型的链接使得它可以下载无法播放的Kb文件。

以下是确定内容类型以确定下载* .extension的代码:

     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]);


        }

它在Console上返回了一个输出列表,其中一行是:

部首:内容类型,值:text / html的;字符集= 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);




    }

3 个答案:

答案 0 :(得分:0)

通常会有一个Content-Type标题,可以为您提供所需文件类型的提示。

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

答案 1 :(得分: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.

答案 2 :(得分: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
        }