Solving the “User cannot be found” error with SPFile.Author

来源:互联网 发布:java开发项目说明文档 编辑:程序博客网 时间:2024/06/05 09:41

I ran into a bug today that was a bit unusual.  We have a custom ASP.NET page that shows information from a custom list in SharePoint 2007.  That page shows details, including the Author, for attachments.  On one particular list item, users started getting a “User cannot be found” error whey they tried to view it with our custom page.  The stack trace showed that it was getting the error in Microsoft.SharePoint.SPFile.get_Author().

It turns out that SPFile stores the user as a login name and tries to resolve the name using SPWeb.SiteUsers, which throws an error if the login name is not found.  The issue was, in this case, the attachment author had been removed from Active Directory and was no longer in SharePoint’s user list, hence the error.

The fix is to go directly to the SPFile properties and get the login name.  Since we can no longer resolve the login name to a user display name, we just display the login name.

string GetAuthorName(SPFile file)
{
    SPUser author = null;
    try { author = file.Author; } catch { }
    return (author == null) ? (string)file.Properties["vti_author"] : author.Name;
}

原创粉丝点击