我正在编写 Windows Phone 8.1(WINRT)应用。
我从服务器获取图像的网址。我想将此URL中的图像保存到localstorage文件。
string PictureUrlFromServer= "http://www.server.com/images/abc.png";
我写了这个:
StorageFolder StorageFolderObject = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFolderAsync(LocalCache, CreationCollisionOption.OpenIfExists);
StorageFile StorageFileObject = await StorageFolderObject.CreateFileAsync(LocalProfilePicName, CreationCollisionOption.ReplaceExisting);
之后该做什么?
修改
我甚至尝试使用下面的代码,但它不起作用:
StorageFolder StorageFolderObject = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFolderAsync(LocalCache, CreationCollisionOption.OpenIfExists);
StorageFile StorageFileObject = await StorageFolderObject.CreateFileAsync(LocalProfilePicName, CreationCollisionOption.ReplaceExisting);
HttpClient HttpClientObject = new HttpClient();
HttpClientObject.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");
Uri UriObject = new Uri(_BitmapImageUriSource);
HttpResponseMessage HttpResponseMessageObject = await HttpClientObject.GetAsync(UriObject);
HttpResponseMessageObject.EnsureSuccessStatusCode();
var responseBuffer = await HttpResponseMessageObject.Content.ReadAsBufferAsync();
await Windows.Storage.FileIO.WriteBufferAsync(StorageFileObject, responseBuffer);
错误: StorageFileObject上的访问被拒绝
答案 0 :(得分:1)
要从网上下载文件,您可以使用HttpClient
。
HttpClient client = new HttpClient(); // Create HttpClient
byte[] buffer = await client.GetByteArrayAsync(PictureUrlFromServer); // Download file
StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync("Image.png", CreationCollisionOption.ReplaceExisting); // Create local file
using (Stream stream = await file.OpenStreamForWriteAsync())
stream.Write(buffer, 0, buffer.Length); // Save