不可能的NullPointerException

时间:2016-05-20 18:27:12

标签: c# wpf nullpointerexception

我有一个C#程序并尝试使用静态方法读取cookie:

[DllImport("wininet.dll", SetLastError = true)]
        public static extern bool InternetGetCookieEx(
        string url,
        string cookieName,
        StringBuilder cookieData,
        ref int size,
        Int32 dwFlags,
        IntPtr lpReserved);

        private const Int32 InternetCookieHttponly = 0x2000;

        /// <summary>
        /// Gets the URI cookie container.
        /// </summary>
        /// <param name="uri">The URI.</param>
        /// <returns></returns>
        public static CookieContainer GetUriCookieContainer(Uri uri)
        {
            CookieContainer cookies = null;
            // Determine the size of the cookie
            int datasize = 8192 * 16;
            StringBuilder cookieData = new StringBuilder(datasize);
            if (!InternetGetCookieEx(uri.ToString(), null, cookieData, ref datasize, InternetCookieHttponly, IntPtr.Zero))
            {
                if (datasize < 0)
                    return null;
                // Allocate stringbuilder large enough to hold the cookie
                cookieData = new StringBuilder(datasize);
                if (!InternetGetCookieEx(
                    uri.ToString(),
                    null, cookieData,
                    ref datasize,
                    InternetCookieHttponly,
                    IntPtr.Zero))
                    return null;
            }
            if (cookieData.Length > 0)
            {
                cookies = new CookieContainer();
                cookies.SetCookies(uri, cookieData.ToString().Replace(';', ','));
            }
            return cookies ?? new CookieContainer();
        }

代码来自此answer

因此,如果cookie为null,我将返回一个新的CookieContainer,它不能为空。

但是当我在我的应用程序中调用此方法时,返回值为null。

var cookie = Util.GetUriCookieContainer(uri);

if (cookie == null)
 {
    MessageBox.Show("cookie is null");
 }

我错过了什么吗?

1 个答案:

答案 0 :(得分:4)

不能为空吗? 那是什么?

if (!InternetGetCookieEx(uri.ToString(), null, cookieData, ref datasize, InternetCookieHttponly, IntPtr.Zero))
{
    if (datasize < 0)
        return null;
    // Allocate stringbuilder large enough to hold the cookie
    cookieData = new StringBuilder(datasize);
    if (!InternetGetCookieEx(
            uri.ToString(),
            null, cookieData,
            ref datasize,
            InternetCookieHttponly,
            IntPtr.Zero))
        return null;
}