2010-05-08 70 views
2

我不確定爲什麼回調方法沒有被全部觸發。我使用VS 2010WebClient DownloadStringCompleted從未在控制檯應用程序中被解僱

static void Main(string[] args) 
     { 
      try 
      { 
       var url = "some link to RSS FEED"; 
       var client = new WebClient(); 
       client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted); 
       client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(client_DownloadDataCompleted); 

       client.DownloadStringAsync(new Uri(url)); 
      } 
      catch (Exception ex) 
      { 
       Console.WriteLine(ex.Message); 
      } 
     } 
     // THIS IS NEVER FIRED 
     static void client_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e) 
     { 
      Console.WriteLine("something"); 
     } 

     // THIS IS NEVER FIRED 
     static void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) 
     { 
      Console.WriteLine("do something"); 

      var rss = XElement.Parse(e.Result); 

      var pictures = from item in rss.Descendants("channel") 
          select new Picture 
          { 
           Name = item.Element("title").Value 
          }; 

      foreach (var picture in pictures) 
      { 
       Console.WriteLine(picture.Name); 
       Console.WriteLine(picture.Url); 
      } 

     } 
+0

你有沒有得到答案? – 2011-04-21 13:42:33

回答

3

如果調用DownloadDataAsync()DownloadDataCompleted事件。如果您撥打DownloadStringAsync()方法,則會觸發DownloadStringCompleted

爲了讓DownloadDataCompleted事件,火災,請嘗試:

static void Main(string[] args) 
     { 
      try 
      { 
       var url = "http://blog.gravitypad.com"; 
       //client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted); 
       client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(client_DownloadDataCompleted); 

       client.DownloadDataAsync(new Uri(url)); 
       Console.ReadLine(); 
      } 
      catch (Exception ex) 
      { 
       Console.WriteLine(ex.Message); 
      } 
     } 
+0

應該提到:DownloadDataAsync將返回結果作爲字節數組,其中DownloadStringAsync將以字符串形式返回結果。 – 2010-05-08 03:33:21

+0

我在上面的代碼中調用DownloadStringAsync方法! – azamsharp 2010-05-08 03:37:45

+0

沒錯,但是您期待着DownloadDataCompleted事件觸發。只有DownloadStringCompleted甚至會觸發...除非你調用DownloadDataAsync。 – 2010-05-08 04:02:24

1

我有這個問題,並意識到URI是不正確的。我的意思是事件不會觸發,除非文件被正確讀取。所以我把我的xml文件放在ClientBin中,它的功能很神奇!

相關問題