我正在制作WP7应用程序,该应用程序下载了我所有的Twitter提要。在此,我想下载所有配置文件图像并将其存储在本地并使用它们,以便每次我打开该应用程序时都将下载它们。请建议采取任何方法。

我正在做什么:使用WebClient下载图像

public MainPage()
    {
        InitializeComponent();

        WebClient client = new WebClient();
        client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
        client.DownloadStringAsync(new Uri("http://www.libpng.org/pub/png/img_png/pnglogo-blk.jpg"));
    }


并将其存储到文件中。

 void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
    {
        using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
        {
            if (myIsolatedStorage.FileExists(fileName1))
                myIsolatedStorage.DeleteFile(fileName1);


            var fileName1 = "Image.jpg";
            using (var fileStream = new IsolatedStorageFileStream(fileName1, FileMode.Create, myIsolatedStorage))
            {
                using (var writer = new StreamWriter(fileStream))
                {
                    var length = e.Result.Length;
                    writer.WriteLine(e.Result);
                }
                var fileStreamLength = fileStream.Length;
                fileStream.Close();
            }
        }


现在我正在尝试将图像设置为BitMapImage

BitmapImage bi = new BitmapImage();

using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
    using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(fileName1, FileMode.Open, FileAccess.Read))
    {
         var fileStreamLength2 = fileStream.Length;
         bi.SetSource(fileStream);
    }
}


但是我无法设置BitmapImage的来源。它抛出System.Exception,没有什么特别的。我做对了吗?我的意思是程序。

编辑另一个观察结果是fileStreamLength和fileStreamLength2是不同的。

最佳答案

您不应该使用DownloadString下载二进制文件。请改用OpenReadAsync,然后将二进制数组保存到隔离存储中。

DownloadString会尝试将您的数据转换为UTF-16文本,这在处理图片时当然不正确。

关于c# - 从url下载图像并在wp7中的图像控件中打开它,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10319817/

10-11 14:25
查看更多