从Windows Server 8.1中的服务器到本地文件的映像

时间:2015-03-02 09:25:30

标签: c# windows-runtime windows-phone windows-phone-8.1 memorystream

我正在编写 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上的访问被拒绝

1 个答案:

答案 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