Detect Mobile Browser in C#.Net

  1. public bool isMobileBrowser()    
  2. {    
  3.     //GETS THE CURRENT USER CONTEXT    
  4.     HttpContext context = HttpContext.Current;    
  5.     
  6.     //FIRST TRY BUILT IN ASP.NT CHECK    
  7.     if (context.Request.Browser.IsMobileDevice)    
  8.     {    
  9.         return true;    
  10.     }    
  11.     //THEN TRY CHECKING FOR THE HTTP_X_WAP_PROFILE HEADER    
  12.     if (context.Request.ServerVariables["HTTP_X_WAP_PROFILE"] != null)    
  13.     {    
  14.         return true;    
  15.     }    
  16.     //THEN TRY CHECKING THAT HTTP_ACCEPT EXISTS AND CONTAINS WAP    
  17.     if (context.Request.ServerVariables["HTTP_ACCEPT"] != null &&    
  18.         context.Request.ServerVariables["HTTP_ACCEPT"].ToLower().Contains("wap"))    
  19.     {    
  20.         return true;    
  21.     }    
  22.     //AND FINALLY CHECK THE HTTP_USER_AGENT     
  23.     //HEADER VARIABLE FOR ANY ONE OF THE FOLLOWING    
  24.     if (context.Request.ServerVariables["HTTP_USER_AGENT"] != null)    
  25.     {    
  26.         //Create a list of all mobile types    
  27.         string[] mobiles =    
  28.             new[]    
  29.         {    
  30.             "midp""j2me""avant""docomo",     
  31.             "novarra""palmos""palmsource",     
  32.             "240x320""opwv""chtml",    
  33.             "pda""windows ce""mmp/",     
  34.             "blackberry""mib/""symbian",     
  35.             "wireless""nokia""hand""mobi",    
  36.             "phone""cdm""up.b""audio",     
  37.             "SIE-""SEC-""samsung""HTC",     
  38.             "mot-""mitsu""sagem""sony"    
  39.             , "alcatel""lg""eric""vx",     
  40.             "NEC""philips""mmm""xx",     
  41.             "panasonic""sharp""wap""sch",    
  42.             "rover""pocket""benq""java",     
  43.             "pt""pg""vox""amoi",     
  44.             "bird""compal""kg""voda",    
  45.             "sany""kdd""dbt""sendo",     
  46.             "sgh""gradi""jb""dddi",     
  47.             "moto""iphone"    
  48.         };    
  49.     
  50.         //Loop through each item in the list created above     
  51.         //and check if the header contains that text    
  52.         foreach (string s in mobiles)    
  53.         {    
  54.             if (context.Request.ServerVariables["HTTP_USER_AGENT"].    
  55.                                                 ToLower().Contains(s.ToLower()))    
  56.             {    
  57.                 return true;    
  58.             }    
  59.         }    
  60.     }    
  61.     
  62.     return false;    
  63. }  
You can call this function as:
  1. if (isMobileBrowser() == true)    
  2. {    
  3.  //code for mobile browser    
  4. }    
  5. else {    
  6.    //code for desktop browser     
  7. }