C# 如何使用Windows.Web.Http下载和存储图像?
如何使用Windows.Web.Http从internet下载jpeg图像并将其存储在Windows应用商店应用程序中 我面临的问题是,我不知道图像必须使用什么Get…Async和Write…Async方法?与字符串相比,文件是非常不同的C# 如何使用Windows.Web.Http下载和存储图像?,c#,windows-phone-8,windows-8,windows-store-apps,windows-phone-8.1,C#,Windows Phone 8,Windows 8,Windows Store Apps,Windows Phone 8.1,如何使用Windows.Web.Http从internet下载jpeg图像并将其存储在Windows应用商店应用程序中 我面临的问题是,我不知道图像必须使用什么Get…Async和Write…Async方法?与字符串相比,文件是非常不同的 仅限Windows.Web.Http 没有第三方解决方案 如果你有其他建议,请使用评论部分,而不是答案。谢谢大家! 您可以使用该方法获取缓冲区,然后调用将缓冲区写入文件: Uri uri = new Uri("http://i.stack.imgur.co
仅限Windows.Web.Http 没有第三方解决方案 如果你有其他建议,请使用评论部分,而不是答案。谢谢大家!
您可以使用该方法获取缓冲区,然后调用将缓冲区写入文件:
Uri uri = new Uri("http://i.stack.imgur.com/ZfLdV.png?s=128&g=1");
string fileName = "daniel2.png";
StorageFile destinationFile = await KnownFolders.PicturesLibrary.CreateFileAsync(
fileName, CreationCollisionOption.GenerateUniqueName);
HttpClient client = new HttpClient();
var buffer = await client.GetBufferAsync(uri);
await Windows.Storage.FileIO.WriteBufferAsync(destinationFile, buffer);
这与John的答案类似,但是在WP8.1中不能使用GetBufferAsync。相反,您可以按照以下方式使用GetStreamAsync:
Uri uri = new Uri(UriString);
string fileName = p4.IconLocation;
HttpClient client = new HttpClient();
var streamImage = await client.GetStreamAsync(uri);
await SaveToLocalFolderAsync(streamImage, fileName);
使用该功能:
public async Task SaveToLocalFolderAsync(Stream file, string fileName)
{
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
StorageFile storageFile = await localFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
using (Stream outputStream = await storageFile.OpenStreamForWriteAsync())
{
await file.CopyToAsync(outputStream);
}
}
为什么不使用这个工具呢?
Uri uri = new Uri(UriString);
string fileName = p4.IconLocation;
HttpClient client = new HttpClient();
var streamImage = await client.GetStreamAsync(uri);
await SaveToLocalFolderAsync(streamImage, fileName);
public async Task SaveToLocalFolderAsync(Stream file, string fileName)
{
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
StorageFile storageFile = await localFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
using (Stream outputStream = await storageFile.OpenStreamForWriteAsync())
{
await file.CopyToAsync(outputStream);
}
}