WindowsIdentity.GetCurrent() 可以返回 null 吗?

2024-01-02

ReSharper 警告我可能发生的情况NullReferenceException in

WindowsIdentity windowsIdentity = new WindowsIdentity(WindowsIdentity.GetCurrent().Token);

我查看了 MSDN 文档,但没有看到任何提及这一点。此外,它没有意义,因为如果您运行可执行文件,则必须登录。

这只是 ReSharper 搜索模式吗?


使用ILSpy,您可以查看反编译版本GetCurrent and GetCurrentInternal, which GetCurrent calls.

获取当前:

public static WindowsIdentity GetCurrent()
{
    return WindowsIdentity.GetCurrentInternal(TokenAccessLevels.MaximumAllowed, false);
}

获取当前内部:

internal static WindowsIdentity GetCurrentInternal(TokenAccessLevels desiredAccess, bool threadOnly)
{
    int errorCode = 0;
    bool flag;
    SafeTokenHandle currentToken = WindowsIdentity.GetCurrentToken(desiredAccess, threadOnly, out flag, out errorCode);
    if (currentToken != null && !currentToken.IsInvalid)
    {
        WindowsIdentity windowsIdentity = new WindowsIdentity();
        windowsIdentity.m_safeTokenHandle.Dispose();
        windowsIdentity.m_safeTokenHandle = currentToken;
        return windowsIdentity;
    }
    if (threadOnly && !flag)
    {
        return null;
    }
    throw new SecurityException(Win32Native.GetMessage(errorCode));
}

Since threadOnly调用时始终为 falseGetCurrent,以及currentToken必须对其他返回语句有效,我不认为你有得到 null 的风险WindowsIdentity.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

WindowsIdentity.GetCurrent() 可以返回 null 吗? 的相关文章

随机推荐