无法将System.String转换为System.Uri

dez*_*kev 13 c# flickr

我正在使用Web客户端类从Internet下载文件(实际上是Flickr).只要我使用这个就可以正常工作:WebClient().DownloadData(string) 但是这会锁定UI,因为它不是异步的.

但是,当我尝试时WebClient().DownloadDatAsync(string),我得到一个编译错误:"无法将System.String转换为System.Uri".

字符串MediumUrl返回 "http://farm4.static.flickr.com/2232/2232/someimage.jpg"

所以问题是如何将字符串转换"http://farm4.static.flickr.com/2232/2232/someimage.jpg"为Uri.

我尝试过的事情 -

  1. 我试图将它投射到Uri,但这也不起作用.
  2. 我试过了Uri myuri = new uri(string)- 如上所述的错误.

    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));  
    }
    
    Run Code Online (Sandbox Code Playgroud)

Dig*_*lex 29

这很好用;

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

顺便说说; 我注意到你错误地输入了新的uri表达式(......,用小写的uri.这不是你的问题,是吗?因为它应该是"new Uri".


Pet*_*lly 6

好的,所以我想如果其他人已经证明你的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);
}
Run Code Online (Sandbox Code Playgroud)

也可以帮助您调试.


Tho*_*que 5

objimage = new MemoryStream(wc.DownloadData(new Uri(photo.MediumUrl)));
Run Code Online (Sandbox Code Playgroud)

b)我尝试过Uri myuri = new uri(string) - 错误如上所述.

这是从字符串创建Uri的常用方法...如果字符串是有效的URI,我不明白为什么它不起作用


Dan*_*ott 5

var yourUri = new UriBuilder(yourString).Uri;
Run Code Online (Sandbox Code Playgroud)

所以你的例子是:

wc.DownloadDataAsync(new UriBuilder(photo.MediumUrl).Uri);
objimage = new MemoryStream(wc.Result);
Run Code Online (Sandbox Code Playgroud)

您可能需要签入以查看操作已完成。

希望有所帮助,