Archive for the ‘C#’ Category

Creating a cookie within a C# plugin in Internet Explorer

June 5, 2007

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.

        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 “” 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.