2014-10-20 29 views
0

在一個應用程序我使一些需要的文件是洪流文件,但我有一個奇怪的問題,每當我通過應用程序下載一個洪流文件的文件結束了腐敗,並將在任何洪流應用程序中打開,我用wptools將它們解壓到一個電腦並測試它,然後在這裏仍然是腐敗的我的代碼我不明白什麼是我做錯了,我是使用webclient相當新。我認爲這與保存文件的方式有關,任何幫助將非常感謝。下載一個洪流文件的結果是腐敗WP8

private void tbLink_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) 
    { 
     string[] linkInfo = (sender as TextBlock).Tag as string[]; 
     fileurl = linkInfo[0]; 
     System.Diagnostics.Debug.WriteLine(fileurl); 
     WebClient client = new WebClient(); 
     client.OpenReadCompleted += client_OpenReadCompleted; 
     client.OpenReadAsync(new Uri(fileurl), linkInfo); 
     client.AllowReadStreamBuffering = true;    
    } 

    async void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e) 
    { 
     string[] linkInfo = e.UserState as string[]; 
     filetitle = linkInfo[1]; 
     filesave = (filetitle);    
     var isolatedfile = IsolatedStorageFile.GetUserStoreForApplication();   
     using (IsolatedStorageFileStream stream = isolatedfile.OpenFile(filesave, System.IO.FileMode.Create)) 
     { 
      byte[] buffer = new byte[e.Result.Length]; 
      while (e.Result.Read(buffer, 0, buffer.Length) > 0) 
      { 
       stream.Write(buffer, 0, buffer.Length); 
      } 
     } 
     try 
     { 
      StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder; 
      StorageFile torrentfile = await local.GetFileAsync(filesave); 
      Windows.System.Launcher.LaunchFileAsync(torrentfile); 
     } 
     catch (Exception) 
     { 
      MessageBox.Show("File Not Found"); 
     } 

回答

1

這是不正確的:

byte[] buffer = new byte[e.Result.Length]; 
while (e.Result.Read(buffer, 0, buffer.Length) > 0) 
{ 
    stream.Write(buffer, 0, buffer.Length); 
} 

Read方法將返回數目的字節讀,它可以是小於buffer.Length。因此,代碼應爲:

int byteCount; 
// Select an appropriate buffer size. 
// This is a buffer, not space for the entire file. 
byte[] buffer = new byte[4096]; 
while ((byteCount = e.Result.Read(buffer, 0, buffer.Length)) > 0) 
{ 
    stream.Write(buffer, 0, byteCount); 
} 

UPDATE:如果數據被壓縮,如您在您的評論張貼的問題,那麼你就可以解壓縮流:

int byteCount; 
byte[] buffer = new byte[4096]; 
using (GZipStream zs = new GZipStream(e.Result, CompressionMode.Decompress)) 
{ 
    while ((byteCount = zs.Read(buffer, 0, buffer.Length)) > 0) 
    { 
     stream.Write(buffer, 0, byteCount); 
    } 
} 

注意我沒有測試過這個代碼,我假設e.Result是一個流。

+0

這些文件仍然是腐敗的,我剛剛遇到這個https://stackoverflow.com/questions/9857709/downloading-a-torrent-file-with-webclient-results-in-corrupt-file但我不知道不知道如何牽連這個 – user1855290 2014-10-20 12:41:52

+1

非常感謝你的幫助,你的血腥天才。 – user1855290 2014-10-20 13:12:27