使用WebClient下载torrent文件会导致文件损坏

时间:2012-03-25 03:27:39

标签: c# .net webclient

我正在尝试在我的.NET应用程序中下载.torrent文件(不是torrent本身的内容)。

使用以下代码适用于其他文件,但不适用于.torrent。生成的文件比通过浏览器下载文件小约1-3kb。在torrent客户端打开它时,它说Torrent已损坏。

WebClient web = new WebClient();
web.Headers.Add("Content-Type", "application/x-bittorrent");
web.DownloadFile("http://kat.ph/torrents/linux-mint-12-gnome-mate-dvd-64-bit-t6008958/", "test.torrent");

在浏览器中打开URL会导致文件正确下载。

关于为什么会发生这种情况的任何想法?是否有正确下载文件的WebClient的替代品?

编辑:我和WebClient一样尝试了这个,结果也是如此:

private void DownloadFile(string url, string file)
    {
        byte[] result;
        byte[] buffer = new byte[4096];

        WebRequest wr = WebRequest.Create(url);
        wr.ContentType = "application/x-bittorrent";
        using (WebResponse response = wr.GetResponse())
        {
            using (Stream responseStream = response.GetResponseStream())
            {
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    int count = 0;
                    do
                    {
                        count = responseStream.Read(buffer, 0, buffer.Length);
                        memoryStream.Write(buffer, 0, count);

                    } while (count != 0);

                    result = memoryStream.ToArray();

                    using (BinaryWriter writer = new BinaryWriter(new FileStream(file, FileMode.Create)))
                    {
                        writer.Write(result);
                    }
                }
            }
        }
    }

1 个答案:

答案 0 :(得分:5)

服务器返回由 gzip 压缩的内容并将此压缩内容下载到文件的问题。对于这种情况,您应该检查“Content-Encoding”标头并使用正确的流阅读器来解压缩源。 我修改了你的函数以处理gzip压缩内容:

private void DownloadFile(string url, string file)
    {
        byte[] result;
        byte[] buffer = new byte[4096];

        WebRequest wr = WebRequest.Create(url);
        wr.ContentType = "application/x-bittorrent";
        using (WebResponse response = wr.GetResponse())
        {
            bool gzip = response.Headers["Content-Encoding"] == "gzip";
            var responseStream = gzip
                                    ? new GZipStream(response.GetResponseStream(), CompressionMode.Decompress)
                                    : response.GetResponseStream();

            using (MemoryStream memoryStream = new MemoryStream())
            {
                int count = 0;
                do
                {
                    count = responseStream.Read(buffer, 0, buffer.Length);
                    memoryStream.Write(buffer, 0, count);
                } while (count != 0);

                result = memoryStream.ToArray();

                using (BinaryWriter writer = new BinaryWriter(new FileStream(file, FileMode.Create)))
                {
                    writer.Write(result);
                }
            }
        }
    }