22

I am using the Web Client Class to download files from the internet (Flickr actually). This works fine as long as I use : WebClient().DownloadData(string) , however this locks up the UI as it is Not asynchronous.

However when I try WebClient().DownloadDatAsync(string), I get a compile error: "Unable to convert System.String to System.Uri".

The string MediumUrl returns "http://farm4.static.flickr.com/2232/2232/someimage.jpg"

So the question is how do I convert the string "http://farm4.static.flickr.com/2232/2232/someimage.jpg" to a Uri.

Things I have tried-

  1. I have tried to cast it to Uri but that does not work either.
  2. I have tried Uri myuri = new uri(string) - errors out as above.

    foreach (Photo photo in allphotos)  
    {  
        //Console.WriteLine(String.Format("photo title is :{0}", photo.Title));
        objimage = new MemoryStream(wc.DownloadData(photo.MediumUrl));
        images.Add(new Pictures(new Bitmap(objimage), photo.MediumUrl, photo.Title));  
    }
    
4

5 回答 5

43

这工作得很好;

System.Uri uri = new System.Uri("http://farm4.static.flickr.com/2232/2232/someimage.jpg");

顺便一提; 我注意到您输入错误的表达式 new uri(...,使用小写的 uri。这不是您的问题,是吗?因为它应该是“new Uri”。

于 2009-09-23T12:40:52.883 回答
8

好的,所以我认为如果其他人已经证明您的 URI 在他们的代码中有效并且可以编译等,并且您还提到它是在运行时生成的 - 可能是您在运行时生成的 UriString 无效,而不是您是什么期待?

我建议不要在尝试从无效字符串创建 Uri 时引发异常,而是建议在Uri类上使用以下方法IsWellFormedUriString 。

string uriString = "your_UriString_here";

if (Uri.IsWellFormedUriString(uriString, UriKind.Absolute))
{
    Uri uri = new Uri(uriString);
}
else
{
    Logger.WriteEvent("invalid uriString: " + uriString);
}

也可能有助于您的调试。

于 2010-04-27T10:26:59.263 回答
5
objimage = new MemoryStream(wc.DownloadData(new Uri(photo.MediumUrl)));

b) I have tried Uri myuri = new uri(string) - errors out as above.

This is the usual way to create a Uri from a string... I don't see why it wouldn't work if the string is a valid URI

于 2009-09-23T12:29:25.213 回答
5
var yourUri = new UriBuilder(yourString).Uri;

So your example would be:

wc.DownloadDataAsync(new UriBuilder(photo.MediumUrl).Uri);
objimage = new MemoryStream(wc.Result);

You may need to put a check in to see the operation has completed.

Hope that helps,

Dan

于 2009-09-23T12:30:31.363 回答
0

If I understand your code correctly, then

wc.DownloadDataAsync(new Uri(photo.MediumUrl));

should work.

于 2009-09-23T12:31:42.193 回答