.NET 5升级至.NET 7控制台项目使用DirectoryServices编译报错求助
.NET 5升级到.NET 7后使用SearchRequest构造函数出现CS0103错误
背景
我需要在C#控制台应用中使用DirectoryServices连接LDAP服务器,由于该服务在.NET 7.0中可用,因此将项目从.NET 5.0升级至.NET 7.0。
复现步骤
- 在控制台执行以下命令:
dotnet new console -f=net5.0 -o=ConsoleFiveToSevencd ConsoleFiveToSevendotnet run
- 修改
ConsoleFiveToSeven.csproj中的<TargetFramework>net5.0</TargetFramework>为<TargetFramework>net7.0</TargetFramework>并保存 - 再次执行
dotnet run,生成\ConsoleFiveToSeven\bin\Debug\net7.0目录 - 执行
dotnet add package System.DirectoryServices.Protocols --version 7.0.0 - 添加指定代码
- 执行
dotnet build
问题情况
- 预期:项目可正常编译
- 实际:出现CS0103错误,提示
distinguishedName、ldapFilter、searchScope和attributeList在当前上下文中不存在
参考构造函数(来自SearchRequest文档)
public SearchRequest (string distinguishedName , string ldapFilter , System.DirectoryServices.Protocols.SearchScope searchScope , params string[] attributeList);
我添加的代码
using System; using System.Net; using System.DirectoryServices.Protocols; namespace ConsoleFiveToSeven { class Program { static void Main(string[] args) { SearchRequest search = new SearchRequest( distinguishedName = "foo", ldapFilter = "foo", searchScope = SearchScope.Subtree, attributeList = new string [] {"cn=foo", "cn=bar", "cn=com"} ); } } }
问题原因与解决办法
问题出在具名参数的语法错误:C#中调用构造函数或方法时,具名参数的正确语法是参数名: 值,而非你使用的参数名 = 值。
修改后的构造函数调用代码如下,即可正常编译:
SearchRequest search = new SearchRequest( distinguishedName: "foo", ldapFilter: "foo", searchScope: SearchScope.Subtree, attributeList: new string [] {"cn", "displayName"} // 注意:这里应填属性名称而非属性=值格式 );
额外说明:attributeList参数用于指定要查询返回的LDAP属性名称(比如cn、displayName),你之前写的"cn=foo"是筛选条件的格式,属于ldapFilter参数的范畴,虽然这不会导致编译错误,但会影响查询结果,建议调整。
内容的提问来源于stack exchange,提问作者surfmuggle
相关产品推荐
相关产品推荐

