other use google search

来源:互联网 发布:类似重生之星际淘宝主 编辑:程序博客网 时间:2024/05/20 06:26

The example simply takes a string that you want to search on http://www.google.com/ for and then displays the first five results that comes back. Nothing major but it does show an ever so slightly more complicated example than the Hello World example above. Anyway, once again, fire up your favorite text editor, type in the code below or copy it from the article and paste it in.

using System;using System.Net;using System.Web;using System.Text;using System.Text.RegularExpressions;namespace Dela.Mono.Examples{   class GoogleSearch   {      static void Main(string[] args)      {         Console.Write("Please enter string to search google for: ");         string searchString = HttpUtility.UrlEncode(Console.ReadLine());                  Console.WriteLine();         Console.Write("Please wait.../r");         // Query google.         WebClient webClient = new WebClient();         byte[] response =              webClient.DownloadData("http://www.google.com/search?&num=5&q="              + searchString);         // Check response for results         string regex = "g><a//shref=/"?(?<URL>[^/">]*)>(?<Name>[^<]*)";         MatchCollection matches                  = Regex.Matches(Encoding.ASCII.GetString(response), regex);         // Output results         Console.WriteLine("===== Results =====");         if(matches.Count > 0)         {            foreach(Match match in matches)            {               Console.WriteLine(HttpUtility.HtmlDecode(                  match.Groups["Name"].Value) +                   " - " + match.Groups["URL"].Value);            }         }         else         {            Console.WriteLine("0 results found");         }      }   }}

Save this file as GoogleExample.cs and go back to the command line. The command to compile this application is a little different to the one we used for the Hello World example. This application makes use of the HttpUtility class which is defined in the System.Web.dll assembly. That means we need to reference this assembly when compiling. To do this you simply use the -r switch. This is the full command you need to type to get this application to compile: mcs GoogleExample.cs -r System.Web.dll
Once again, the previous command assumes that your command prompt is working in the same directory as the GoogleExample.cs file and that the Mono directories have been added to your path if you are using Windows.

As with the Hello World example you can run this application from the command line using mono GoogleExample.exe or mint GoogleExample.exe - Take your pick. The same compiled assembly will run on Windows and Linux. You can test this by compiling it on Windows, copying the assembly to a Linux machine and running the mono GoogleExample.exe command there.

原创粉丝点击