C# map network drive sample

reference:http://www.eggheadcafe.com/community/csharp/2/64575/map-network-drive.aspx
Project property: platform target must be Any CPU!! Must  on x64!! don't know the reason.

if x86, can map success, but don't appear in windows explorer, so must set to Any CPU ,map success ,can appear in windows explorer. 

namespace WpfMapHelper
{
    [StructLayout(LayoutKind.Sequential)]
    public struct NETRESOURCEA
    {
        public int dwScope;
        public int dwType;
        public int dwDisplayType;
        public int dwUsage;
        [MarshalAs(UnmanagedType.LPStr)]
        public string lpLocalName;
        [MarshalAs(UnmanagedType.LPStr)]
        public string lpRemoteName;
        [MarshalAs(UnmanagedType.LPStr)]
        public string lpComment;
        [MarshalAs(UnmanagedType.LPStr)]
        public string lpProvider;
        public override String ToString()
        {
            String str = "LocalName: " + lpLocalName + " RemoteName: " + lpRemoteName
                + " Comment: " + lpComment + " lpProvider: " + lpProvider;
            return (str);
        }
    }



 
    public static class NetworkDrive
    {
        [DllImport("mpr.dll")]
        public static extern int WNetAddConnection2A(
            [MarshalAs(UnmanagedType.LPArray)] NETRESOURCEA[] lpNetResource,
            [MarshalAs(UnmanagedType.LPStr)] string lpPassword,
            [MarshalAs(UnmanagedType.LPStr)] string UserName,
            int dwFlags);

        public static void test()
        {
            NETRESOURCEA[] n = new NETRESOURCEA[1];
            n[0] = new NETRESOURCEA();
            n[0].dwScope = 2;
            n[0].dwType = 0x1;
            n[0].dwDisplayType = 3;
            n[0].dwUsage = 1;
            int dwFlags = 0x00000001;
            n[0].lpLocalName = @"z:";
            n[0].lpRemoteName = @"\\192.168.82.133\public";
            n[0].lpProvider = null;
            Console.WriteLine(n[0]);
            int res = WNetAddConnection2A(n, null, null, dwFlags);
            if (res != 0)
                throw new System.ComponentModel.Win32Exception(res);
            Console.WriteLine("WNetAddConnection3 returned : " + res);
            Console.WriteLine(n[0]);
        }
    }

}

 

 

 

posted @ 2012-07-27 09:24  xiaokang088  阅读(850)  评论(0编辑  收藏  举报