Expand Minimize

Use GetListByUrl to get lists by URL.

PnP has an implementation to get lists by URL.

CheckId SPC029008
TypeName UseGetListByUrl
Severity Warning
Type Assembly

Standard SharePoint CSOM

var webRelativeUrl = "SiteAssets";
var baseExpressions = new List<Expression<Func<List, object>>> { l => l.DefaultViewUrl, l => l.Id, l => l.BaseTemplate, l => l.OnQuickLaunch, l => l.DefaultViewUrl, l => l.Title, l => l.Hidden, l => l.RootFolder };

if (expressions != null && expressions.Any())
{
    baseExpressions.AddRange(expressions);
}
if (string.IsNullOrEmpty(webRelativeUrl)) throw new ArgumentNullException(nameof(webRelativeUrl));

if (!web.IsObjectPropertyInstantiated("ServerRelativeUrl"))
{
    web.Context.Load(web, w => w.ServerRelativeUrl);
    web.Context.ExecuteQueryRetry();
}
var listServerRelativeUrl = UrlUtility.Combine(web.ServerRelativeUrl, webRelativeUrl);

var foundList = web.GetList(listServerRelativeUrl);
web.Context.Load(foundList, baseExpressions.ToArray());
try
{
web.Context.ExecuteQueryRetry();
}
catch (ServerException se)
{
    if (se.ServerErrorTypeName == "System.IO.FileNotFoundException")
    {
    foundList = null;
    }
    else
    {
        throw;
    }
}
var list = foundList;

Using PnP
var list = web.GetListByUrl("SiteAssets");

To suppress this violation in managed code add the following attribute to the method which contains the instruction (available since SPCAF version v5.2). Learn more about SuppressMessage here.

// Important: Ensure to have #define CODE_ANALYSIS at the beginning of your .cs file
[SuppressMessage("Rencore.Analyzers.Assemblies.Rules.PnP.PnPBestPracticesGroup", "SPC029008:UseGetListByUrl", Justification = "Provide reason for suppression here")]
Disclaimer: The views and opinions expressed in this documentation and in SPCAF do not necessarily reflect the opinions and recommendations of Microsoft or any member of Microsoft. SPCAF and RENCORE are registered trademarks of Rencore. All other trademarks, service marks, collective marks, copyrights, registered names, and marks used or cited by this documentation are the property of their respective owners.