You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.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=ConsoleFiveToSeven
    • cd ConsoleFiveToSeven
    • dotnet 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 11:40:21