如何使用WebResponse下载.wmv文件

时间:2009-07-26 04:05:13

标签: c# .net windows-media-player

我正在使用以下代码通过WebResponse获取wmv文件。我正在使用一个线程调用此函数:

static void GetPage(object data)
{
    // Cast the object to a ThreadInfo
    ThreadInfo ti = (ThreadInfo)data;

    // Request the URL
    WebResponse wr = WebRequest.Create(ti.url).GetResponse();

    // Display the value for the Content-Length header
    Console.WriteLine(ti.url + ": " + wr.Headers["Content-Length"]);
    string toBeSaved = @"C:\Users\Kevin\Downloads\TempFiles" + wr.ResponseUri.PathAndQuery;        
    StreamWriter streamWriter = new StreamWriter(toBeSaved);

    MemoryStream m = new MemoryStream();
    Stream receiveStream = wr.GetResponseStream();
    using (StreamReader sr = new StreamReader(receiveStream))
    {
        while (sr.Peek() >= 0)
        {
            m.WriteByte((byte)sr.Read());
        }
        streamWriter.Write(sr.ReadToEnd());
        sr.Close();
        wr.Close();
    }

    streamWriter.Flush();
    streamWriter.Close();

    // streamReader.Close();
    // Let the parent thread know the process is done
    ti.are.Set();

    wr.Close();
}

该文件似乎下载得很好,但Windows Media Viewer无法正常打开文件。关于无法支持文件类型的一些愚蠢错误。

我错过了什么非常容易的事情?

3 个答案:

答案 0 :(得分:5)

您只需将其下载为二进制而不是文本。这是一种应该为你做的技巧。

public void DownloadFile(string url, string toLocalPath)
{
    byte[] result = null;
    byte[] buffer = new byte[4097];

    WebRequest wr = WebRequest.Create(url);

    WebResponse response = wr.GetResponse();
    Stream responseStream = response.GetResponseStream;
    MemoryStream memoryStream = new MemoryStream();

    int count = 0;

    do {
        count = responseStream.Read(buffer, 0, buffer.Length);
        memoryStream.Write(buffer, 0, count);

        if (count == 0) {
            break;
        }
    }
    while (true);

    result = memoryStream.ToArray;

    FileStream fs = new FileStream(toLocalPath, FileMode.OpenOrCreate, FileAccess.ReadWrite);

    fs.Write(result, 0, result.Length);

    fs.Close();
    memoryStream.Close();
    responseStream.Close();
}

答案 1 :(得分:4)

我不明白你为什么一次填充一个字节的MemoryStream m ,然后将 sr 写入文件。那时,我相信 sr 是空的,而且永远不会使用MemoryStream m

下面是我写的一些代码来完成类似的任务。它一次获得32K块的WebResponse,并将其直接转储到文件中。

public void GetStream()
{
    // ASSUME: String URL is set to a valid URL.
    // ASSUME: String Storage is set to valid filename.

    Stream response = WebRequest.Create(URL).GetResponse().GetResponseStream();
    using (FileStream fs = File.Create(Storage)) 
    {
        Byte[] buffer = new Byte[32*1024];
        int read = response.Read(buffer,0,buffer.Length);
        while (read > 0)
        {
            fs.Write(buffer,0,read);
            read = response.Read(buffer,0,buffer.Length);
        }
    }
    // NOTE: Various Flush and Close of streams and storage not shown here.
}

答案 2 :(得分:2)

您正在使用StreamReaderStreamWriter来传输您的信息流,但这些课程用于处理文字。您的文件是二进制文件,并且在传输数据时可能会破坏CR,LF和CR LF的序列。如何处理NUL字符我不知道。