/* * This work is licensed under the Creative Commons Attribution 2.5 License. * To view a copy of this license, visit http://creativecommons.org/licenses/by/2.5/ * or send a letter to Creative Commons, 543 Howard Street, 5th Floor, * San Francisco, California, 94105, USA. * * Original developer: David Betz * */ using System; using System.Collections.Generic; using System.Text; using System.Net; using System.IO; using System.Xml; namespace FeedBuilder { class FeedFormatDetector { public static AbstractReader Detect(Uri uri) { return Detect(uri.AbsoluteUri); } public static AbstractReader Detect(String url) { if (!url.StartsWith("http://") && !url.StartsWith("https://")) { throw new FeedReaderException("Feed url must begin with either http:// or https://"); } String feedData = ""; HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url); using (HttpWebResponse myHttpWebResponse = (HttpWebResponse)myRequest.GetResponse()) { using (Stream streamResponse = myHttpWebResponse.GetResponseStream()) { using (StreamReader streamRead = new StreamReader(streamResponse)) { Char[] readBuffer = new Char[256]; int count = streamRead.Read(readBuffer, 0, 256); StringBuilder builder = new StringBuilder(); while (count > 0) { String resultData = new String(readBuffer, 0, count); Console.WriteLine(resultData); builder.Append(resultData); count = streamRead.Read(readBuffer, 0, 256); } feedData = builder.ToString().Trim(); } } } AbstractReader reader; XmlDocument doc = new XmlDocument(); doc.Load(url); if (doc.DocumentElement != null && doc.DocumentElement.ChildNodes != null) { if (doc.DocumentElement.Name.ToLower() == "rss") { // Yes this loads the URL again... RSS.NET simply would NOT let // me pass it the data. Perhaps they will fix this bug in the // future. reader = new RssReader(url); } else if (doc.DocumentElement.Name.ToLower() == "feed") { reader = new AtomReader(feedData); } else { throw new FeedReaderException("Unknown feed format"); } } else { throw new FeedReaderException("Invalid feed"); } return reader; } } }