1

将 amnd write 和 IO.Stream(在我的情况下从 Internet 下载的 Zip 文件)读取到 ApplicationData.Current.LocalFolder 的最佳方法是什么

我试过

public static async Task WriteToFile(
       this System.IO.Stream input,
       string fileName,
       StorageFolder folder = null)
    {
        folder = folder ?? ApplicationData.Current.LocalFolder;
        var file = await folder.CreateFileAsync(
            fileName,
            CreationCollisionOption.ReplaceExisting);
        using (var fs = await file.OpenAsync(FileAccessMode.ReadWrite))
        {
            using (var outStream = fs.GetOutputStreamAt(0))
            {
                using (var dataWriter = new DataWriter(outStream))
                {
                    byte[] buffer = new byte[8 * 1024];
                    int len;
                    while ((len = input.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        dataWriter.WriteBytes(buffer);
                    }

                    await dataWriter.StoreAsync();
                    dataWriter.DetachStream();
                }

                await outStream.FlushAsync();
            }
        }
    }

用于写作和

StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(filename);
var fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
var stream = fileStream.AsStreamForRead();

但是文件在途中的某个地方损坏了。我认为读取没有问题,所以它应该在写入文件的某个地方。有没有更好的方法将 IO.Stream 写入 ApplicationData.Current.LocalFolder 有效?

4

1 回答 1

0

试试这个:

static async void DownloadFileAsync(
    this HttpClient httpClient,
    string requestUri,
    string fileName,
    StorageFolder folder = null)
{
    folder = folder ?? ApplicationData.Current.LocalFolder;

    var file = await folder.CreateFileAsync(
        fileName, CreationCollisionOption.ReplaceExisting);

    using (var httpStream = await httpClient.GetStreamAsync(uri))
    using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
    {
        await httpStream.CopyToAsync(fileStream.AsStreamForWrite());
    }
}

MSDN:HttpClient 类HttpClient.GetStreamAsync 方法WindowsRuntimeStreamExtensions.AsStreamForWrite 方法Stream.CopyToAsync 方法

于 2012-04-26T10:28:27.680 回答