Home
Manage Your Code
Snippet: Check for Mobile Devices (C#)
Title: Check for Mobile Devices Language: C#
Description: Check for Mobile Devices Views: 148
Author: izoeasy izoeasy Date Added: 11/29/2007
Copy Code  
1
2
3<add key="MobileDevices" value="(nokia|sonyericsson|blackberry|samsung|sec-|windows ce|motorola|mot-|up.b)" />
4
5Then I wrote a property called IsMobile which tries the Request.Browser.IsMobileDevice property first, and then tries the regular expression afterwards.
6
7private static readonly Regex MOBILE_REGEX = new Regex(ConfigurationManager.AppSettings.Get("MobileDevices"), RegexOptions.IgnoreCase | RegexOptions.Compiled);
8
9 
10
11public static bool IsMobile
12
13{
14
15  get
16
17  {
18
19    HttpContext context = HttpContext.Current;
20
21    if (context != null)
22
23    {
24
25      HttpRequest request = context.Request;
26
27      if (request.Browser.IsMobileDevice)
28
29        return true;
30
31 
32
33      if (!string.IsNullOrEmpty(request.UserAgent) && MOBILE_REGEX.IsMatch(request.UserAgent))
34
35        return true;
36
37    }
38
39 
40
41    return false;
42
43  }
44
45}
46