我正在尝试获取本地网络计算机的列表。我尝试使用NetServerEnum
和WNetOpenEnum
API,但这两个API都返回错误代码6118 (ERROR_NO_BROWSER_SERVERS_FOUND)
。不使用本地网络中的Active Directory。
大多数奇怪的Windows资源管理器都显示所有本地计算机没有任何问题。
是否还有其他方法可以获取局域网中的计算机列表?
答案 0 :(得分:14)
您需要使用System.DirectoryServices命名空间并尝试以下操作:
DirectoryEntry root = new DirectoryEntry("WinNT:");
foreach (DirectoryEntry computers in root.Children)
{
foreach (DirectoryEntry computer in computers.Children)
{
if (computer.Name != "Schema")
{
textBox1.Text += computer.Name + "\r\n";
}
}
}
它对我有用。
答案 1 :(得分:11)
我使用接口IShellItem和CSIDL_NETWORK找到了解决方案。我得到了所有的网络电脑。
C ++:使用方法IShellFolder :: EnumObjects
C#:您可以使用Gong Solutions Shell Library
using System.Collections;
using System.Collections.Generic;
using GongSolutions.Shell;
using GongSolutions.Shell.Interop;
public sealed class ShellNetworkComputers : IEnumerable<string>
{
public IEnumerator<string> GetEnumerator()
{
ShellItem folder = new ShellItem((Environment.SpecialFolder)CSIDL.NETWORK);
IEnumerator<ShellItem> e = folder.GetEnumerator(SHCONTF.FOLDERS);
while (e.MoveNext())
{
Debug.Print(e.Current.ParsingName);
yield return e.Current.ParsingName;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
答案 2 :(得分:6)
我用它做了一个功能。 SchemaClassName
必须是计算机
public List<string> NetworkComputers()
{
return (
from Computers
in (new DirectoryEntry("WinNT:")).Children
from Computer
in Computers.Children
where Computer.SchemaClassName == "Computer"
orderby Computer.Name
select Computer.Name).ToList;
}
答案 3 :(得分:2)
对toddmo的答案的一个小扩展,如果您不喜欢LINQ查询样式语法并希望还包括工作组作为选项:
public IEnumerable<string> VisibleComputers(bool workgroupOnly = false) {
Func<string, IEnumerable<DirectoryEntry>> immediateChildren = key => new DirectoryEntry("WinNT:" + key)
.Children
.Cast<DirectoryEntry>();
Func<IEnumerable<DirectoryEntry>, IEnumerable<string>> qualifyAndSelect = entries => entries.Where(c => c.SchemaClassName == "Computer")
.Select(c => c.Name);
return (
!workgroupOnly ?
qualifyAndSelect(immediateChildren(String.Empty)
.SelectMany(d => d.Children.Cast<DirectoryEntry>()))
:
qualifyAndSelect(immediateChildren("//WORKGROUP"))
).ToArray();
}
答案 4 :(得分:2)
这是一个使用LINQ查询的属性
SELECT *
FROM Table1 AS [To]
WHERE not Exists (Select top 5 *
from Table1 as Ti
where To.ID = Ti.ID
order by Ti.ID)
答案 5 :(得分:1)
使用LINQ lambda语法和非托管资源解析器的解决方案
public List<String> GetNetworkHostNames()
{
using (var directoryEntry = new DirectoryEntry("WinNT:"))
{
return directoryEntry
.Children
.Cast<DirectoryEntry>()
.SelectMany(x=>x.Children.Cast<DirectoryEntry>())
.Where(c => c.SchemaClassName == "Computer")
.Select(c => c.Name)
.ToList();
}
}