Freigeben über


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

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