ReSharper警告我可能存在的NullReferenceException
WindowsIdentity windowsIdentity = new WindowsIdentity(WindowsIdentity.GetCurrent().Token);我查看了MSDN文档,但没有看到任何提及.另外,这没有意义,因为如果您运行可执行文件,则必须先登录. 这只是ReSharper的搜索模式吗?
解决方案使用ILSpy,您可以查看GetCurrent和GetCurrentInternal的反编译版本,它们被GetCurrent调用. 结果是:
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的风险./p>
ReSharper warns me about a possible NullReferenceException in
WindowsIdentity windowsIdentity = new WindowsIdentity(WindowsIdentity.GetCurrent().Token);I looked in MSDN doc but didn't see any mention of this. Also, it doesn't make sense since if you run an executable, you have to be logged on. Is this just a ReSharper search pattern?
解决方案Using ILSpy, you can look at a de-compiled version of GetCurrent and GetCurrentInternal, which GetCurrent calls. The result is:
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)); }Since threadOnly is always false when calling from GetCurrent, and the currentToken must be valid for the other return statement, I don't think you're at risk of getting a null WindowsIdentity.
更多推荐
WindowsIdentity.GetCurrent()是否可以返回null?
发布评论