【问题标题】:How can i write HttpStreamContent to file?如何将 HttpStreamContent 写入文件?
【发布时间】:2016-03-25 10:56:44
【问题描述】:

这是我下载文件的代码。 但我不确定如何将文件写入磁盘。

private async Task DownloadFile()
    {
        HttpStreamContent streamContent = new HttpStreamContent(new SlowInputStream(streamLength));
        IProgress<HttpProgress> progress = new Progress<HttpProgress>(ShowProgress);
        response = await httpClient.PostAsync(new Uri(downloadUrl), streamContent).AsTask(cts.Token, progress);
    }

我不知道在这里写什么以及在哪里调用 WriteToFile():

  private async Task WriteToFile()
    {
        var myFile = await KnownFolders.MusicLibrary.CreateFileAsync(filename.Replace("---", " - ")+".mp3", CreationCollisionOption.GenerateUniqueName);
///stuck here
    }

【问题讨论】:

  • 您需要将响应写入文件吗?请澄清
  • 响应包含什么?文件内容?

标签: c# file windows-runtime windows-phone-8.1 http-streaming


【解决方案1】:

我是这样工作的:

private async Task DownloadFile()
    {

        IProgress<HttpProgress> progress = new Progress<HttpProgress>(ShowProgress);
        try
        {

            response = await httpClient.GetAsync(new Uri(downloadUrl), HttpCompletionOption.ResponseContentRead).AsTask(cts.Token, progress);
            DownloadMessageText.Text = "Download complete. Writing to disk...";
            await WriteToFile();
            DownloadMessageText.Text = "File saved in music library.";
        }
        catch { }


    }

并写入磁盘:

private async Task WriteToFile()
    {
        var myFile = await KnownFolders.MusicLibrary.CreateFileAsync(filename.Replace("---", " - ") + ".mp3", CreationCollisionOption.GenerateUniqueName);
        var fs = await myFile.OpenAsync(FileAccessMode.ReadWrite);
        IBuffer buffer = await response.Content.ReadAsBufferAsync();
        await fs.WriteAsync(buffer);
    }

【讨论】:

    猜你喜欢
    • 2013-10-15
    • 2018-02-25
    • 2015-10-12
    • 1970-01-01
    • 1970-01-01
    • 2019-06-08
    • 2019-01-15
    • 1970-01-01
    • 2013-03-01
    相关资源
    最近更新 更多