我正在尝试查找网络上的所有计算机。以下代码在Win7-32位上运行良好,但在Win7-64位上出现以下错误。
NetServerEnum()返回代码-6118。
public sealed class NetworkBrowser
{
[DllImport("Netapi32", CharSet = CharSet.Auto, SetLastError = true), SuppressUnmanagedCodeSecurityAttribute]
public static extern int NetServerEnum(
string serverName,
int dwLevel,
ref IntPtr pBuf,
int dwPrefMaxLen,
out int dwEntriesRead,
out int dwTotalEntries,
int dwServerType,
string domain,
out int dwResumeHandle
);
[DllImport("Netapi32", SetLastError = true), SuppressUnmanagedCodeSecurity]
public static extern int NetApiBufferFree(IntPtr pBuf);
[StructLayout(LayoutKind.Sequential)]
public struct ServerInfo100
{
internal int sv100_platform_id;
[MarshalAs(UnmanagedType.LPWStr)]
internal string sv100_name;
}
public static ArrayList GetNetworkComputers()
{
ArrayList networkComputers = new ArrayList();
const int MAX_PREFERRED_LENGTH = -1;
int SV_TYPE_WORKSTATION = 1;
int SV_TYPE_SERVER = 2;
IntPtr buffer = IntPtr.Zero;
IntPtr tmpBuffer = IntPtr.Zero;
int entriesRead;
int totalEntries;
int resHandle;
int sizeofInfo = Marshal.SizeOf(typeof(ServerInfo100));
try
{
int ret = NetServerEnum(null, 100, ref buffer,
MAX_PREFERRED_LENGTH, out entriesRead, out totalEntries,
SV_TYPE_WORKSTATION | SV_TYPE_SERVER, null, out resHandle);
if (ret == 0)
{
for (int i = 0; i < totalEntries; i++)
{
tmpBuffer = new IntPtr((int)buffer +(i * sizeofInfo));
ServerInfo100 svrInfo = (ServerInfo100)
Marshal.PtrToStructure(tmpBuffer,
typeof(ServerInfo100));
networkComputers.Add(svrInfo.sv100_name);
}
}
}
catch (Exception ex)
{
return null;
}
finally
{
NetApiBufferFree(buffer);
}
return networkComputers;
}
}我已经在谷歌上搜索了很多,但还没有找到这个场景的任何解决方案。
发布于 2014-10-23 23:37:11
我认为,这恰好回答了你的问题。
Retrieving a list of network computer names using C# - Code project article comment
错误和解决方案-设计指南- 25-Feb-14 23:46
我读到过,有些人在基于x64的系统上使用这段代码时遇到了问题。它可能与指针操作有关,更准确地说,这一行是代码中断的地方:
tmpBuffer = new IntPtr((int)buffer + (i * sizeofINFO));
由于在x64系统上,地址空间的宽度为64位,因此代码应更改为:
tmpBuffer = new IntPtr((long)buffer + (i * sizeofINFO));
在此更改之后,一切都应该正常工作。致以最好的问候!
发布于 2013-12-11 15:38:24
也许这会有帮助
http://social.msdn.microsoft.com/Forums/windows/en-US/1107608f-ef56-4719-a5e5-f6966d111043/win32-api-compatibility-on-windows-7-64-bit?forum=winforms
当你将应用程序的目标平台设置为'AnyCPU‘时,默认情况下,它将在64位机器上运行在64位模式下,在32位机器上运行在32位模式下。现在,假设你的应用程序在64位模式下运行,在某个时刻,它必须调用一些特定于32位机器的应用程序接口或代码(比如你的PrintDlg应用程序接口)。但是,由于你的进程已经在64位模式下运行,你的32位代码无法加载,因此它将失败。
bit将目标平台设置为x86 -您的应用程序将始终在32位和64位计算机上以32位模式运行。由于应用程序始终在32位模式下运行,因此也可以毫无问题地调用32位组件或API。现在,唯一的问题是-如果你有任何64位特定的组件,它不能被调用(因为64位代码不能在32位进程中运行)。但我不认为这对你专门为64位机器设计应用程序来说是个问题。“
发布于 2015-07-03 13:52:03
您的函数完全是通过使用以下注释来工作的:
[DllImport("Netapi32", CharSet = CharSet.Unicode, SetLastError = true)]而是:
[DllImport("Netapi32", CharSet = CharSet.Auto, SetLastError = true), SuppressUnmanagedCodeSecurityAttribute]致以问候。
https://stackoverflow.com/questions/20512242
复制相似问题