开发者

WebClient DownloadStringCompleted Never Fired in Console Application

开发者 https://www.devze.com 2022-12-29 08:01 出处:网络
I am not sure why the callback methods are not fired AT ALL. I am using VS 2010. static void Main(string[] args)

I am not sure why the callback methods are not fired AT ALL. I am using VS 2010.

 static void Main(string[] args)
        {
            try
            {
                var url = "some link to RSS FE开发者_开发技巧ED"; 
                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);
            }

        }


The DownloadDataCompleted event is fired if you call the DownloadDataAsync() method. DownloadStringCompleted is fired if you call the DownloadStringAsync() method.

To get the DownloadDataCompleted event to fire, try:

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);  
            } 
        } 


I had this problem and realized that the uri was not correct. I mean the event wont fire unless the file is read correctly. So I placed my xml file in ClientBin and it worked like magic!

0

精彩评论

暂无评论...
验证码 换一张
取 消