下载torrent文件结果是损坏的WP8

本文关键字:WP8 损坏 结果是 torrent 文件 下载 | 更新日期: 2023-09-27 18:27:13

在一个应用程序中,我正在制作一些所需的文件是torrent文件,但我遇到了一个奇怪的问题,每当我通过该应用程序下载torrent时,这些文件都会损坏,无法在任何torrent应用程序中打开,我使用wptools将它们提取到pc上并进行测试,但仍然损坏了。这是我的代码,我看不出有什么错,我对使用Web客户端还很陌生。我想这与我保存文件的方式有关。任何帮助都将不胜感激。

   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");
        }

下载torrent文件结果是损坏的WP8

这是不正确的:

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