加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Windows > 正文

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

发布时间:2020-12-13 20:08:58 所属栏目:Windows 来源:网络整理
导读:ReSharper警告我可能的NullReferenceException WindowsIdentity windowsIdentity = new WindowsIdentity(WindowsIdentity.GetCurrent().Token); 我查看了MSDN文档,但没有看到任何提及.此外,它没有意义,因为如果您运行可执行文件,则必须先登录. 这只是一个ReS
ReSharper警告我可能的NullReferenceException
WindowsIdentity windowsIdentity = new WindowsIdentity(WindowsIdentity.GetCurrent().Token);

我查看了MSDN文档,但没有看到任何提及.此外,它没有意义,因为如果您运行可执行文件,则必须先登录.
这只是一个ReSharper搜索模式吗?

使用ILSpy,您可以查看GetCurrent和GetCurrentInternal的解编译版本,GetCurrent调用GetCurrentInternal.
结果是:

GetCurrent:

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

GetCurrentInternal:

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));
}

因为从GetCurrent调用时ThreadOnly总是为false,而且currentToken必须对另一个return语句有效,我不认为你有获得一个空的WindowsIdentity的风险.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读