Creating a cookie within a C# plugin in Internet Explorer

I had the need to create a cookie from within my IE plug-in. I create a session cookie when the browser is loaded so that when a user visits my site, I know what version of the plug-in is installed. There appears to be no direct C# API to do this (based on a few google searches). I did find from these searches that there is a method called InternetSetCookie in wininet.dll

For those who don’t regularly have to jump out into the COM world, the code to do this can be a bit of a pain to track down, so here’s the C# import of the method as well as a nice wrapper that will throw an exception if the call is not successful.

        [DllImport("wininet.dll",EntryPoint="InternetSetCookie",ExactSpelling=false,CharSet=CharSet.Unicode,SetLastError=true)]
        static extern bool InternetSetCookie(string url, string cookieName, string cookieData);

        public static void SetCookie(string siteUrl, string cookieName, string cookieData)
        {
            if (!InternetSetCookie(siteUrl, cookieName, cookieData))
            {
                throw new Exception("Exception setting cookie: Win32 Error code="+Marshal.GetLastWin32Error());
            }
        }

Note that siteUrl must be in the form of “http://www.abc.com” and cannot include a port specification.

For reference the MSDN entry for InternetSetCookie is here.

More details on how to specify the expiration dates of the cookies is here.

And in case you want even more info on cookies in IE, this page describes each of the possible cookie fields in detail.

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: