如何使用 Windows.Web.Http 在客户端设备上下载文件

How to download a file on the client device using Windows.Web.Http

我正在开发 Windows 到 UWP 应用程序。存在一个 Web 服务,当调用 (GET) 时,returns 一个文件。当使用浏览器触发网络服务时,它成功地在浏览器上下载了一个文件。

在 UWP 应用程序上,我使用 Windows.Web.Http 调用网络服务。我需要保存获取网络服务发送的文件并将其保存在设备上。

我目前有以下代码。不确定如何从 Web 服务获取结果并保存到文件中。

public async Task DownloadFile(string WebServiceURL, string PathToSave)
{

    var myFilter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
    myFilter.AllowUI = false;
    Windows.Web.Http.HttpClient client = new Windows.Web.Http.HttpClient(myFilter);
    Windows.Web.Http.HttpResponseMessage result = await client.GetAsync(new Uri(WebServiceURL));


    using (IInputStream inputStream = await result.Content.ReadAsInputStreamAsync())
    {
        //not sure if this is correct and if it is, how to save this to a file
    }

}

使用 System.Web.Http,我可以使用以下方法轻松完成此操作:

Stream stream = result.Content.ReadAsStreamAsync().Result;
var fileStream = File.Create(PathToSave);
await stream.CopyToAsync(fileStream);
fileStream.Dispose();
stream.Dispose();

但是,使用 Windows.Web.Http,我不确定我该怎么做。请帮忙!

这是您要找的东西? 像这样?

var myFilter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
            myFilter.AllowUI = false;
            Windows.Web.Http.HttpClient client = new Windows.Web.Http.HttpClient(myFilter);
            Windows.Web.Http.HttpResponseMessage result = await client.GetAsync(new Uri(WebServiceURL));

            //not sure if this is correct and if it is, how to save this to a file
            var file = await ApplicationData.Current.LocalFolder.CreateFileAsync("filename.tmp", CreationCollisionOption.GenerateUniqueName);
            using (var filestream = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                await result.Content.WriteToStreamAsync(filestream);
                await filestream.FlushAsync();

            }