我正在尝试使用名为.dll的Windows netapi32.dll来操作DFS共享。我们在Windows 2008 R2上使用DFS,我使用的是.NET 4.0。我以前从未在.NET中使用过这样的东西,但是我很难理解什么是失败。
我正在使用DllImport调用NetDfsGetInfo来测试获取DFS共享的信息。我必须为我想从函数中接收到的信息级别创建结构。
public struct DFS_INFO_3
{
[MarshalAs(UnmanagedType.LPWStr)]
public string EntryPath;
[MarshalAs(UnmanagedType.LPWStr)]
public string Comment;
public UInt32 State;
public UInt32 NumberOfStorages;
public IntPtr Storage;
}
public struct DFS_STORAGE_INFO
{
public ulong State;
[MarshalAs(UnmanagedType.LPWStr)]
public string ServerName;
[MarshalAs(UnmanagedType.LPWStr)]
public string ShareName;
}我使用了以下代码来获取和读取结果:
[DllImport("netapi32", CallingConvention = CallingConvention.Winapi)]
public static extern int NetDfsGetInfo(
[MarshalAs(UnmanagedType.LPWStr)] string DfsEntryPath,
[MarshalAs(UnmanagedType.LPWStr)]string ServerName,
[MarshalAs(UnmanagedType.LPWStr)]string ShareName,
int Level,
out IntPtr Buffer);
public void GetInfo() {
IntPtr buffer;
string dfsPath = "\\\\server\\share";
int result = NetDfsGetInfo(EntryPath, null, null, 3, out buffer);
if (result == 0) { //0 is Success
DFS_INFO_3 info = (DFS_INFO_3)Marshal.PtrToStructure(buffer, typeof(DFS_INFO_3));
DFS_STORAGE_INFO storage = (DFS_STORAGE_INFO)Marshal.PtrToStructure(info.Storage, typeof(DFS_STORAGE_INFO)); //Error
Console.WriteLine("{0}, {1}, {2} ", storage.ServerName, storage.ShareName, storage.State);
}
}在阅读storage行之前,一切都进行得很顺利。
我有时得到一个错误,上面写着:
运行时遇到了致命错误。在线程0x1d44上,错误地址为0x626ac91c。错误代码为0xc0000005。此错误可能是CLR中的错误,也可能是用户代码中不安全或不可验证部分中的错误。此错误的常见来源包括COM-interop或PInvoke的用户封送错误,这可能会损坏堆栈。
错误类型是fatalExecutionEngineError,它不是.NET异常,所以我无法捕获它。这并不是每次都会发生,但我要说的是,大约50%的时间我都会犯这个错误。查找窗口错误码,我看到5是“访问被拒绝”。作为只精通入门级Comp的人,我对指针(这就是IntPtr对象)有一点了解,并且指针可能已经溢出到了它不应该有的结果中?我仍然不明白为什么这个错误只会在某些时候发生。
我如何理解/避免这个错误?
发布于 2012-07-09 16:07:22
您对DFS_STORAGE_INFO的定义是错误的。在.NET中,long/ulong是64位,而在非托管Win32中只有32位(与int/uint相同)
public struct DFS_STORAGE_INFO
{
public UInt32 State;
[MarshalAs(UnmanagedType.LPWStr)]
public string ServerName;
[MarshalAs(UnmanagedType.LPWStr)]
public string ShareName;
}当您封送DFS_STORAGE_INFO时,您将读取结构结束后的4个字节--这可能工作,也可能不工作,这取决于结构后面的内容。
https://stackoverflow.com/questions/11398749
复制相似问题