提交对函数内使用块返回的 DirectoryEntry 的更改
我将展示我对 using 语句在 C# 中如何工作的无知。
我正在尝试编写一个函数,该函数接受活动目录中用户的唯一标识符并返回该用户。然后我想对用户进行更改并提交它们。
我怀疑这不起作用,因为我正在使用块中返回。
这是基本想法:
public static DirectoryEntry GetADUser( string prop1Value, string prop2Value )
{
using( var rootDE = new DirectoryEntry(LDAPPath, User, Password))
{
using( var searcher = new DirectorySearcher(rootDE))
{
searcher.Filter = string.Format("(&(prop1={0})(prop2={1}))", prop1Value, prop2Value);
var user = searcher.FindOne().GetDirectoryEntry();
return user;
}
}
}
//...
var user = GetADUser("val1","val2");
user.Properties["prop3"].Value = "Spagetti";
user.CommitChanges();
这可行吗?活动目录似乎没有显示我以这种方式所做的更改。调用提交更改时我没有收到任何异常。
这与:可以从在 using 块内 和 会发生什么什么时候“return”是从“using”块中调用的吗?。
如果它不能以这种方式工作,如果我在不使用 using 块的情况下重写该函数,情况会有多糟糕?
I'm going to show my ignorance about how using statements work in c# I think.
I am trying to write a function that takes in unique identifiers for a user in active directory and returns that user. I then want to make changes to the user and commit them.
I suspect this isn't working because I'm returning in a using block.
Here is the basic idea:
public static DirectoryEntry GetADUser( string prop1Value, string prop2Value )
{
using( var rootDE = new DirectoryEntry(LDAPPath, User, Password))
{
using( var searcher = new DirectorySearcher(rootDE))
{
searcher.Filter = string.Format("(&(prop1={0})(prop2={1}))", prop1Value, prop2Value);
var user = searcher.FindOne().GetDirectoryEntry();
return user;
}
}
}
//...
var user = GetADUser("val1","val2");
user.Properties["prop3"].Value = "Spagetti";
user.CommitChanges();
Would that work? It doesn't seem like active directory is showing changes I make in that way. I'm not getting any exceptions when calling commit changes.
This is related to: Is it OK doing a return from inside using block and What happens when 'return' is called from within a 'using' block?.
If it won't work this way, how bad could it get if I rewrote that function without the using blocks?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将您的用户声明为 using 块之外的 SearchResult,然后将其分配到 using(var searcher....) 块中,然后将 return 语句放在 using 块末尾之后,
即
您还可以通过更改搜索器来简化操作使用块
declare your user as a SearchResult outside of the using blocks then assign it in the using(var searcher....) block then put your return statement after the end of the using block
i.e
you can also streamline things a bit by changing the searcher using block
不要对 Value Spagetti 进行硬编码
另外,如果 user.Properties["prop3"].Value 给出并错误尝试,
如果它的整数强制转换为整数,这是否有意义..?
如果用户不在提交的 using 内部,您将无法访问用户。因此,将提交移至 using 内部。
Don't hard code the Value Spagetti
also if user.Properties["prop3"].Value gives and error try
if its an integer cast as integer does this make sense..?
you will not be able to access user if it's not inside of the using in regards to the commit.. so move the commit inside the using..