C# 下载torrent文件结果是WP8损坏

C# 下载torrent文件结果是WP8损坏,c#,windows-phone-8,visual-studio-2013,C#,Windows Phone 8,Visual Studio 2013,在一个应用程序中,我正在制作一些所需的文件是torrent文件,但我有一个奇怪的问题,每当我通过应用程序下载torrent文件时,这些文件最终都会损坏,无法在任何torrent应用程序中打开,我使用wptools将其解压缩到pc并进行测试,但仍然损坏我的代码,我看不出我做错了什么,我对使用webclient相当陌生。我想这与我保存文件的方式有关任何帮助都会很好谢谢 private void tbLink_MouseLeftButtonDown(object sender, MouseBut

在一个应用程序中,我正在制作一些所需的文件是torrent文件,但我有一个奇怪的问题,每当我通过应用程序下载torrent文件时,这些文件最终都会损坏,无法在任何torrent应用程序中打开,我使用wptools将其解压缩到pc并进行测试,但仍然损坏我的代码,我看不出我做错了什么,我对使用webclient相当陌生。我想这与我保存文件的方式有关任何帮助都会很好谢谢

   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");
        }
这是不正确的:

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);
}
更新:如果数据被压缩,如您在评论中发布的问题,那么您可以解压缩流:

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
是一个流。

文件仍然损坏,我刚刚遇到了这个问题,但我不知道如何牵连到这一点。非常感谢你的帮助,你是个该死的天才。