将(读)IO.Stream写入(来自)ApplicationData.Current.LocalFolder

时间:2012-04-26 09:54:29

标签: c# windows-8 microsoft-metro

读取amnd write和IO.Stream(在我的案例中从互联网下载的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?

1 个答案:

答案 0 :(得分: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:Http­Client ClassHttp­Client.­Get­Stream­Async MethodWindows­Runtime­Stream­Extensions.­As­Stream­For­Write MethodStream.­Copy­To­Async Method