2009-07-26 62 views
5

我正在使用以下代碼通過WebResponse獲取wmv文件。我正在使用一個線程來調用此函數:如何使用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無法正確打開該文件。一些關於無法支持文件類型的愚蠢錯誤。

我錯過了什麼令人難以置信的容易的事情?

+0

您是否已驗證Windows Media Viewer是否在您的應用程序之外正常打開該文件? – thedz 2009-07-26 04:08:05

+0

是的。應該已經清楚了。 – KevDog 2009-07-26 04:10:34

回答

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(); 
} 
4

我不明白爲什麼您要填寫的MemoryStream 一個字節的時間,但隨後寫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

您使用的是StreamReaderStreamWriter轉移你的數據流,但這些類是處理文本。你的文件是二進制文件,當傳輸數據時,CR,LF和CR LF的序列可能會被破壞。 NUL字符如何處理我不知道。