C# - Windows Server 2008 和 IIS7 上来自 NetApi32.dll 的 NetUseAdd

标签 c# winapi iis-7 interop

我正在尝试使用 NetUseAdd 添加应用程序所需的共享。我的代码如下所示。

[DllImport("NetApi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern uint NetUseAdd(
     string UncServerName,
     uint Level,
     IntPtr Buf,
     out uint ParmError);

...

USE_INFO_2 info = new USE_INFO_2();
info.ui2_local = null;
info.ui2_asg_type = 0xFFFFFFFF;
info.ui2_remote = remoteUNC;
info.ui2_username = username;
info.ui2_password = Marshal.StringToHGlobalAuto(password);
info.ui2_domainname = domainName;

IntPtr buf = Marshal.AllocHGlobal(Marshal.SizeOf(info));

try
{
    Marshal.StructureToPtr(info, buf, true);

    uint paramErrorIndex;
    uint returnCode = NetUseAdd(null, 2, buf, out paramErrorIndex);

    if (returnCode != 0)
    {
        throw new Win32Exception((int)returnCode);
    }
}
finally
{
    Marshal.FreeHGlobal(buf);
}

这在我们的服务器 2003 机器上运行良好。但是在尝试转移到 Server 2008 和 IIS7 时,这不再有效。通过自由日志记录,我发现它卡在 Marshal.StructureToPtr(info, buf, true);

行上

我完全不知道为什么这是任何人都可以阐明它告诉我在哪里可以找到更多信息吗?

最佳答案

原因是:

您从 pinvoke.net 上提取了 p/invoke 签名,但您没有验证它。最初编写此 p/invoke 示例代码的傻瓜不知道他在做什么,并创建了一个在 32 位系统上“工作”但在 64 位系统上不起作用的代码。他以某种方式将一个非常简单的 p/invoke 签名变成了一些非常复杂的困惑,并在网上像野火一样传播开来。

正确的签名是:

    [DllImport( "NetApi32.dll", SetLastError = true, CharSet = CharSet.Unicode )]
    public static extern uint NetUseAdd(
         string UncServerName,
         UInt32 Level,
         ref USE_INFO_2 Buf,
         out UInt32 ParmError
        );

    [StructLayout( LayoutKind.Sequential, CharSet = CharSet.Unicode )]
    public struct USE_INFO_2
    {
        public string ui2_local;
        public string ui2_remote;
        public string ui2_password;
        public UInt32 ui2_status;
        public UInt32 ui2_asg_type;
        public UInt32 ui2_refcount;
        public UInt32 ui2_usecount;
        public string ui2_username;
        public string ui2_domainname;
    }

你的代码应该是:

USE_INFO_2 info = new USE_INFO_2();   
info.ui2_local = null;   
info.ui2_asg_type = 0xFFFFFFFF;   
info.ui2_remote = remoteUNC;   
info.ui2_username = username;   
info.ui2_password = password;
info.ui2_domainname = domainName;      

uint paramErrorIndex;   
uint returnCode = NetUseAdd(null, 2, ref info, out paramErrorIndex);   

if (returnCode != 0)   
{   
    throw new Win32Exception((int)returnCode);   
}

希望对您有所帮助。我只花了半天的时间远程调试别人的垃圾代码,试图弄清楚发生了什么,就是这样。

关于C# - Windows Server 2008 和 IIS7 上来自 NetApi32.dll 的 NetUseAdd,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1102538/

相关文章:

c# - 使用 MVVM 代码绑定(bind)对 ListBox 进行排序

c# - 反射 : Getting members from inherited interface, 但不是来自继承类

c++ - VK_CONTROL/VK_MENU/VK_SHIFT 的默认值

asp.net-mvc - 在 IIS 7/Server 2008 上部署 ASP.NET MVC 应用程序的最佳方式?

c# - 在 C# 中设置电子邮件附件名称

c# - 来自外部函数的锁定和引用值

c++ - IME - 如何处理按键

http - 解码 URL 中的变音符号(或复合编码与预组合编码)

Asp.net 检测 iis 是否具有域的 https 证书?

visual-studio-2010 - Crystal Report 不会在浏览器中显示