locked
get url from browser in C#

    Question

  • hi ebody,
                  i am developing an application in which i need to get the url from the browser's address bar.
    please any one can help me. i am using C# language not asp.net. i know it can be done using combination of Clipboard and keybd_event(). i can fetch url form IE but i am having problem with mozzilla. plz help me!. if any one can do it in a different way you are most welcome.
    Wednesday, October 07, 2009 11:20 AM

All replies

  • Check this out:
    namespace Library.Net.DataStructs
    {
        [StructLayout(LayoutKind.Sequential)]
        public struct INTERNET_CACHE_ENTRY_INFO
        {
            public UInt32 dwStructSize;
            public string lpszSourceUrlName;
            public string lpszLocalFileName;
            public UInt32 CacheEntryType;
            public UInt32 dwUseCount;
            public UInt32 dwHitRate;
            public UInt32 dwSizeLow;
            public UInt32 dwSizeHigh;
            public FILETIME LastModifiedTime;
            public FILETIME ExpireTime;
            public FILETIME LastAccessTime;
            public FILETIME LastSyncTime;
            public IntPtr lpHeaderInfo;
            public UInt32 dwHeaderInfoSize;
            public string lpszFileExtension;
            public UInt32 dwExemptDelta;
        } ;
        public class InternetCacheEntryInfo
        {
            public override string ToString()
            {
                return this.SourceUrlName;
            }
    
            internal InternetCacheEntryInfo(INTERNET_CACHE_ENTRY_INFO entry)
            {
                this.CacheEntryType = entry.CacheEntryType;
                this.ExemptDelta = entry.dwExemptDelta;
                this.ExpireTime = entry.ExpireTime.ToDateTime();
                this.FileExtension = entry.lpszFileExtension;
                this.HeaderInfo = entry.lpHeaderInfo;
                this.HitRate = entry.dwHitRate;
                this.LastAccessTime = entry.LastAccessTime.ToDateTime();
                this.LastModifiedTime = entry.LastModifiedTime.ToDateTime();
                this.LastSyncTime = entry.LastSyncTime.ToDateTime();
                this.LocalFileName = entry.lpszLocalFileName;
                this.SourceUrlName = entry.lpszSourceUrlName.Substring(entry.lpszSourceUrlName.IndexOf("@") + 1);
                this.UseCount = entry.dwUseCount;
            }
    
            public string SourceUrlName
            {
                get;
                private set;
            }
    
            public string LocalFileName
            {
                get;
                private set;
            }
    
            public UInt32 CacheEntryType
            {
                get;
                private set;
            }
    
            public UInt32 UseCount
            {
                get;
                private set;
            }
    
            public UInt32 HitRate
            {
                get;
                private set;
            }
    
            public DateTime LastModifiedTime
            {
                get;
                private set;
            }
    
            public DateTime ExpireTime
            {
                get;
                private set;
            }
    
            public DateTime LastAccessTime
            {
                get;
                private set;
            }
    
            public DateTime LastSyncTime
            {
                get;
                private set;
            }
    
            public IntPtr HeaderInfo
            {
                get;
                private set;
            }
    
            public string FileExtension
            {
                get;
                private set;
            }
    
            public UInt32 ExemptDelta
            {
                get;
                private set;
            }
        }
    
        public enum UrlCacheType
        {
            Cookie,
            Visited,
        }
    }
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.InteropServices;
    using System.Text.RegularExpressions;
    using Library.Net.DataStructs;
    using Library.Win32.Natives;
    using Library.Win32.Natives.IfacesEnumsStructsClasses;
    
    namespace Library.Net
    {
        public sealed class InternetCache
        {
            /// <summary>
            /// UrlCache functionality is taken from:
            /// Scott McMaster (EMAIL REMOVED)
            /// CodeProject article
            /// 
            /// There were some issues with preparing URLs
            /// for RegExp to work properly. This is
            /// demonstrated in AllForms.SetupCookieCachePattern method
            /// 
            /// urlPattern:
            /// . Dump the entire contents of the cache.
            /// Cookie: Lists all cookies on the system.
            /// Visited: Lists all of the history items.
            /// Cookie:.*\.example\.com Lists cookies from the example.com domain.
            /// http://www.example.com/example.html$: Lists the specific named file if present
            /// \.example\.com: Lists any and all entries from *.example.com.
            /// \.example\.com.*\.gif$: Lists the .gif files from *.example.com.
            /// \.js$: Lists the .js files in the cache.
            /// </summary>
            /// <param name="urlPattern"></param>
            /// <returns></returns>
            private static IEnumerable<INTERNET_CACHE_ENTRY_INFO> FindUrlCacheEntries(string urlPattern)
            {
                var results = new List<INTERNET_CACHE_ENTRY_INFO>();
    
                var buffer = IntPtr.Zero;
                UInt32 structSize;
    
                //This call will fail but returns the size required in structSize
                //to allocate necessary buffer
                var hEnum = Api.FindFirstUrlCacheEntry(null, buffer, out structSize);
                try
                {
                    if (hEnum == IntPtr.Zero)
                    {
                        var lastError = Marshal.GetLastWin32Error();
                        switch (lastError)
                        {
                            case Hresults.ERROR_INSUFFICIENT_BUFFER:
                                buffer = Marshal.AllocHGlobal((int)structSize);
                                hEnum = Api.FindFirstUrlCacheEntry(urlPattern, buffer, out structSize);
                                break;
                            case Hresults.ERROR_NO_TOKEN:
                            case Hresults.ERROR_NO_MORE_ITEMS:
                                return results.AsEnumerable();
                        }
                    }
    
                    var result = (INTERNET_CACHE_ENTRY_INFO)Marshal.PtrToStructure(buffer, typeof(INTERNET_CACHE_ENTRY_INFO));
                    try
                    {
                        if (Regex.IsMatch(result.lpszSourceUrlName, urlPattern, RegexOptions.IgnoreCase))
                            results.Add(result);
                    }
                    catch (ArgumentException ae)
                    {
                        throw new ApplicationException("Invalid regular expression, details=" + ae.Message);
                    }
    
                    if (buffer != IntPtr.Zero)
                    {
                        try
                        {
                            Marshal.FreeHGlobal(buffer);
                        }
                        catch
                        {
                        }
                        buffer = IntPtr.Zero;
                    }
    
                    while (true)
                    {
                        var nextResult = Api.FindNextUrlCacheEntry(hEnum, buffer, out structSize);
                        structSize *= 4;
                        if (nextResult != 1) //TRUE
                        {
                            var lastError = Marshal.GetLastWin32Error();
                            switch (lastError)
                            {
                                case Hresults.ERROR_INSUFFICIENT_BUFFER:
                                    buffer = Marshal.AllocHGlobal((int)structSize);
                                    Api.FindNextUrlCacheEntry(hEnum, buffer, out structSize);
                                    break;
                                case Hresults.ERROR_NO_MORE_ITEMS:
                                case Hresults.ERROR_INVALID_PARAMETER:
                                    return results.AsEnumerable();
                            }
                        }
    
                        if (buffer != IntPtr.Zero)
                        {
                            result = (INTERNET_CACHE_ENTRY_INFO)Marshal.PtrToStructure(buffer, typeof(INTERNET_CACHE_ENTRY_INFO));
                            if (Regex.IsMatch(result.lpszSourceUrlName, urlPattern, RegexOptions.IgnoreCase))
                                results.Add(result);
    
    
                            try
                            {
                                Marshal.FreeHGlobal(buffer);
                            }
                            catch
                            {
                            }
                            buffer = IntPtr.Zero;
                        }
                    }
                }
                finally
                {
                    if (hEnum != IntPtr.Zero)
                        Api.FindCloseUrlCache(hEnum);
                    if (buffer != IntPtr.Zero)
                        try
                        {
                            Marshal.FreeHGlobal(buffer);
                        }
                        catch
                        {
                        }
                }
            }
    
            public static IEnumerable<InternetCacheEntryInfo> FindUrlCacheEntries(UrlCacheType type)
            {
                foreach (var entry in FindUrlCacheEntries(type + ":"))
                    yield return new InternetCacheEntryInfo(entry);
            }
        }
    }
    Paste it in your code and simply useit:
    Library.Net.InternetCache.FindUrlCacheEntries(Library.Net.DataStructs.UrlCacheType.Visited);

    Mohammad - C# Lover
    Wednesday, October 07, 2009 11:43 AM
  • This code will get data from the browser cache. However, if I understand the question correctly, he wants to find out what the Url typed into the browser address bar is.
    feroze
    --
    My blog
    Instruction on how to create a tracelog with your System.Net application
    Wednesday, October 07, 2009 6:04 PM
  • hi, thankx for ur code!
    i vll need a little more help from u,
    i m getting this error from the above code
    "Error    1    The type or namespace name 'Win32' does not exist in the namespace 'Library' (are you missing an assembly reference?)"
    can u help me please!
    bye and thankx!!!
    Thursday, October 08, 2009 4:31 AM
  • Hi, You were right, That code has a simple bug. I've written the code down again, Please check the following code again.

    namespace Library.Net.DataStructs
    {
        [StructLayout(LayoutKind.Sequential)]
        public struct INTERNET_CACHE_ENTRY_INFO
        {
            public UInt32 dwStructSize;
            public string lpszSourceUrlName;
            public string lpszLocalFileName;
            public UInt32 CacheEntryType;
            public UInt32 dwUseCount;
            public UInt32 dwHitRate;
            public UInt32 dwSizeLow;
            public UInt32 dwSizeHigh;
            public FILETIME LastModifiedTime;
            public FILETIME ExpireTime;
            public FILETIME LastAccessTime;
            public FILETIME LastSyncTime;
            public IntPtr lpHeaderInfo;
            public UInt32 dwHeaderInfoSize;
            public string lpszFileExtension;
            public UInt32 dwExemptDelta;
        } ;
        }
    
    
    namespace Library.Net
    {
        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Runtime.InteropServices;
        using System.Text.RegularExpressions;
        using DataStructs;
    
        public sealed class InternetCache
        {
            private const int ERROR_INVALID_PARAMETER = 87;
            private const int ERROR_INSUFFICIENT_BUFFER = 122;
            private const int ERROR_NO_MORE_ITEMS = 259;
            private const int ERROR_NO_TOKEN = 1008;
            
            /// <summary>
            /// UrlCache functionality is taken from:
            /// Scott McMaster (EMAIL REMOVED)
            /// CodeProject article
            /// 
            /// There were some issues with preparing URLs
            /// for RegExp to work properly. This is
            /// demonstrated in AllForms.SetupCookieCachePattern method
            /// 
            /// urlPattern:
            /// . Dump the entire contents of the cache.
            /// Cookie: Lists all cookies on the system.
            /// Visited: Lists all of the history items.
            /// Cookie:.*\.example\.com Lists cookies from the example.com domain.
            /// http://www.example.com/example.html$: Lists the specific named file if present
            /// \.example\.com: Lists any and all entries from *.example.com.
            /// \.example\.com.*\.gif$: Lists the .gif files from *.example.com.
            /// \.js$: Lists the .js files in the cache.
            /// </summary>
            /// <param name="urlPattern"></param>
            /// <returns></returns>
            public static IEnumerable<INTERNET_CACHE_ENTRY_INFO> FindUrlCacheEntries(string urlPattern)
            {
                var results = new List<INTERNET_CACHE_ENTRY_INFO>();
    
                var buffer = IntPtr.Zero;
                UInt32 structSize;
    
                //This call will fail but returns the size required in structSize
                //to allocate necessary buffer
                var hEnum = FindFirstUrlCacheEntry(null, buffer, out structSize);
                try
                {
                    if (hEnum == IntPtr.Zero)
                    {
                        var lastError = Marshal.GetLastWin32Error();
                        switch (lastError)
                        {
                            case ERROR_INSUFFICIENT_BUFFER:
                                buffer = Marshal.AllocHGlobal((int)structSize);
                                hEnum = FindFirstUrlCacheEntry(urlPattern, buffer, out structSize);
                                break;
                            case ERROR_NO_TOKEN:
                            case ERROR_NO_MORE_ITEMS:
                                return results.AsEnumerable();
                        }
                    }
    
                    var result = (INTERNET_CACHE_ENTRY_INFO)Marshal.PtrToStructure(buffer, typeof(INTERNET_CACHE_ENTRY_INFO));
                    try
                    {
                        if (Regex.IsMatch(result.lpszSourceUrlName, urlPattern, RegexOptions.IgnoreCase))
                            results.Add(result);
                    }
                    catch (ArgumentException ae)
                    {
                        throw new ApplicationException("Invalid regular expression, details=" + ae.Message);
                    }
    
                    if (buffer != IntPtr.Zero)
                    {
                        try
                        {
                            Marshal.FreeHGlobal(buffer);
                        }
                        catch
                        {
                        }
                        buffer = IntPtr.Zero;
                    }
    
                    while (true)
                    {
                        var nextResult = FindNextUrlCacheEntry(hEnum, buffer, out structSize);
                        structSize *= 4;
                        if (nextResult != 1) //TRUE
                        {
                            var lastError = Marshal.GetLastWin32Error();
                            switch (lastError)
                            {
                                case ERROR_INSUFFICIENT_BUFFER:
                                    buffer = Marshal.AllocHGlobal((int)structSize);
                                    FindNextUrlCacheEntry(hEnum, buffer, out structSize);
                                    break;
                                case ERROR_NO_MORE_ITEMS:
                                case ERROR_INVALID_PARAMETER:
                                    return results.AsEnumerable();
                            }
                        }
    
                        if (buffer != IntPtr.Zero)
                        {
                            result = (INTERNET_CACHE_ENTRY_INFO)Marshal.PtrToStructure(buffer, typeof(INTERNET_CACHE_ENTRY_INFO));
                            if (Regex.IsMatch(result.lpszSourceUrlName, urlPattern, RegexOptions.IgnoreCase))
                                results.Add(result);
    
    
                            try
                            {
                                Marshal.FreeHGlobal(buffer);
                            }
                            catch
                            {
                            }
                            buffer = IntPtr.Zero;
                        }
                    }
                }
                finally
                {
                    if (hEnum != IntPtr.Zero)
                        FindCloseUrlCache(hEnum);
                    if (buffer != IntPtr.Zero)
                        try
                        {
                            Marshal.FreeHGlobal(buffer);
                        }
                        catch
                        {
                        }
                }
            }
    
            [DllImport("wininet.dll", SetLastError = true)]
            private static extern IntPtr FindFirstUrlCacheEntry(string lpszUrlSearchPattern,
                                                               IntPtr lpFirstCacheEntryInfo,
                                                               out UInt32 lpdwFirstCacheEntryInfoBufferSize);
            [DllImport("wininet.dll", SetLastError = true)]
            private static extern long FindNextUrlCacheEntry(IntPtr hEnumHandle,
                                                            IntPtr lpNextCacheEntryInfo,
                                                            out UInt32 lpdwNextCacheEntryInfoBufferSize);
    
            [DllImport("wininet.dll", SetLastError = true)]
            private static extern long FindCloseUrlCache(IntPtr hEnumHandle);
    
        }
    }
    
    And this is how to use:
    namespace ConsoleApplication553
    {
        class Program
        {
            static void Main()
            {
                foreach (var entry in Library.Net.InternetCache.FindUrlCacheEntries("Visited:"))
                {
                    Console.WriteLine(entry.lpszSourceUrlName);
                }
                Console.ReadKey();
            }
        }
    }

    Mohammad - C# Lover
    Saturday, October 10, 2009 9:45 AM
  • Hi,

    Mohammad Mir Mustafa,this is just for IE what about other BROWSERS?

    Arsalan

    Wednesday, June 09, 2010 3:16 PM
  • i dont get output.

    its shows the so many errors.

    plz help me knw.

    Saturday, March 12, 2011 1:33 PM
  • Hi, Mohammad, Also U have Any idea About the Web Filtering Project.

    Which Lang is best for that.

    Plz its Urgent. Plz Help me.


    Saturday, March 12, 2011 1:36 PM
  • This s wat im searching for..

    Im getting errors. Can u upload/mail me full project file.?


    Cholavendhan

    Wednesday, February 29, 2012 8:13 PM
  • Hi Mohammad,

    I am looking for similer sort of application. Can you please help me out.. Can you provide solution project so that I can check it out.

    Please its bit urgent.

    Thanks In Advance.

    Regards,

    Nithin Eate

    Thursday, August 09, 2012 10:31 AM
  • HttpContext.Current.Request.Url
    Wednesday, October 24, 2012 12:40 PM