WebClient下载许多文件错误 - 无效的URI:URI为空

时间:2012-09-15 17:54:00

标签: c# webclient last.fm webclient-download

我想从last.fm下载所有专辑艺术家,每个封面都被命名为专辑标题。 但是当启动程序时,我收到一个错误:“无效的URI:URI为空。”

程序代码:

public static void GetXML()
        {
            string url = @"http://ws.audioscrobbler.com/2.0/?method=artist.gettopalbums&artist=radiohead&api_key=b25b959554ed76058ac220b7b2e0a026";
            string albumName = String.Empty;
            string coverLink = String.Empty;
            int[] numArr = new int[30];

            for (int x = 1; x < numArr.Length; x++)
            {
                numArr[x] = x;   
            }

           XDocument xml = XDocument.Load(url);

           foreach (var c in numArr)
           {
               var name = xml.XPathSelectElements(String.Format("//album[@rank='{0}']", c))
                             .Select(x => x.Element("name").Value)
                             .ToList();
               foreach (var item in name)
               {
                   albumName = item.ToString();
               }

               var covers = xml.XPathSelectElements(String.Format("//album[@rank='{0}']/image[@size='extralarge']", c))
                          .Select(x => x.Value)
                          .ToList();
               foreach (var item in covers)
               {
                   coverLink = item.ToString();
               }

               WebClient web = new WebClient();
               web.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(web_DownloadFileCompleted);
               web.DownloadFileAsync(new Uri(coverLink), @"X:\Code\T\" + albumName + ".jpg");
           }

        }

1 个答案:

答案 0 :(得分:0)

您将数组初始化为

for (int x = 1; x < numArr.Length; x++)
{
      numArr[x] = x;   
}

但从未设置numArr[0]中使用的值foreach (var c in numArr)(并且没有排名为0的相册)。

这不是更容易吗?

 var albums = xml.Descendants("album")
        .Select(a => new
        {
            Rank = (int)a.Attribute("rank"),
            Name = a.Element("name").Value,
            ImageUrl = a.XPathSelectElement("image[@size='extralarge']").Value
        })
        .ToList();