Twitter Search via C#

By on 4/27/2009

While there are some examples of accessing the Twitter API via C# on the web, I couldn’t really find any good samples of how to do a search.  There were some examples that took the REST route and used raw http requests.  While others explored the JSON formatting capabilities of the twitter API.  In the end, I didn’t really care for a lot of the code I saw, and I wasn’t really concerned with what format I got the results in, just that I got the results.

After a bit of fiddling about, I decided to use the ATOM format, and the SyndicationFeed API that came with WCF.  I came up with this simple command line tool that lets you type a search query, and it’ll list the top 10 results.  The code is quite short and simple to understand.
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("twitter -> ");
            var input = Console.ReadLine();

while (input != "exit") { var scrubbed = HttpUtility.UrlEncode(input); var reader = XmlReader.Create( string.Format("http://search.twitter.com/search.atom?lang=en&q={0}", scrubbed)); var feed = SyndicationFeed.Load(reader);

foreach (SyndicationItem item in feed.Items) { Console.WriteLine("\t{0} - {1}", item.Authors[0].Name, item.Title.Text); }

Console.Write("\ntwitter -> "); input = Console.ReadLine(); } } }
To use it, you just need to add references to System.ServiceModel.dll, and System.Web.dll.

Enjoy!

See more in the archives