C# - 下载已损坏

时间:2016-03-07 08:09:46

标签: c# android xamarin download

所以我有一个Xamarin android应用程序可以从服务器上下载文件,但图像有时会严重失真(下面的截图),视频无法播放,音频听起来很奇怪等等,但大多数时候它被下载正常。而这些扭曲主要发生在移动网络上,当通过wifi下载时,它们的发生频率较低。我的下载代码是否有问题,或者保存位置可能与它有关?

下载文件的代码:

public static async Task DownloadFileAsync(string url, string mimeType, Stream fileStream) {
    long receivedBytes = 0;
    long totalBytes = 0;
    WebClient client = new WebClient ();

    using (var stream = await client.OpenReadTaskAsync (url)) {
        byte[] buffer = new byte[1024];
        totalBytes = Int64.Parse (client.ResponseHeaders [System.Net.HttpResponseHeader.ContentLength]);
        for (;;) {
            int bytesRead = await stream.ReadAsync (buffer, 0, buffer.Length);
            await fileStream.WriteAsync (buffer, 0, buffer.Length);

            if (bytesRead == 0)
            {
                await Task.Yield();
                break;
            }

            receivedBytes += bytesRead;

            //Raise an event
            DownloadProgressMade (receivedBytes, totalBytes);
        }
    }
}

文件会像这样保存:

//act = Activity, because downloads are started from a fragment
outFile = act.OpenFileOutput(filename, FileCreationMode.WorldReadable);
await UploadHelper.DownloadFileAsync(url, mimeType, outFile);

以下是下载图片的屏幕截图: Screenshot

更新:不仅图像失真,而且其他文件也会损坏 - 视频有时无法播放,音频文件听起来很奇怪。

0 个答案:

没有答案