zoukankan      html  css  js  c++  java
  • .NET创建映射磁盘

    .NET(C#) 在网络上创建映射磁盘

    (在服务器a上创建服务器b的共享磁盘并访问目录)

     

    1、  在文件服务器上创建共享目录,并新建访问账户。比如共享目录为:\\192.168.0.9\share访问账户为:administrator 密码为:123.com

    (C#只需创建公共类WNetHelper 调用即可)

    2、  在WEB服务器上新建用户:administrator 密码为:123.com,用户组选择默认的administrator组即可。

    3、  在WEB项目中新建公共类WNetHelper

    public class WNetHelper

        {

            [DllImport("mpr.dll", EntryPoint = "WNetAddConnection2")]

     

            private static extern uint WNetAddConnection2(NetResource lpNetResource, string lpPassword, string lpUsername, uint dwFlags);

     

     

     

            [DllImport("Mpr.dll", EntryPoint = "WNetCancelConnection2")]

     

            private static extern uint WNetCancelConnection2(string lpName, uint dwFlags, bool fForce);

     

     

     

            [StructLayout(LayoutKind.Sequential)]

     

            public class NetResource

            {

     

                public int dwScope;

     

     

     

                public int dwType;

     

     

     

                public int dwDisplayType;

                public int dwUsage;

     

                public string lpLocalName;

     

                public string lpRemoteName;

     

                public string lpComment;

     

                public string lpProvider;

     

            }

       /// <summary>

     

      /// 为网络共享做本地映射

     

      /// </summary>

     

    /// <param name="username">访问用户名(windows系统需要加计算机名,如:comp-1\user-1</param>

     

     /// <param name="password">访问用户密码</param>

     

     /// <param name="remoteName">网络共享路径(如:\\192.168.0.9\share)</param>

     

     /// <param name="localName">本地映射盘符</param>

     

     /// <returns></returns>

     

     public static uint WNetAddConnection(string username, string password, string remoteName, string localName)

            {

     

                NetResource netResource = new NetResource();

     

                netResource.dwScope = 2;

     

                netResource.dwType = 1;

     

                netResource.dwDisplayType = 3;

     

                netResource.dwUsage = 1;

     

                netResource.lpLocalName = localName;

     

                netResource.lpRemoteName = remoteName.TrimEnd('\\');

     

                uint result = WNetAddConnection2(netResource, password, username, 0);

     

                return result;

     

            }

     

            public static uint WNetCancelConnection(string name, uint flags, bool force)

            {

     

                uint nret = WNetCancelConnection2(name, flags, force);

     

                return nret;

     

            }

     

        }

    }

    4、  为IIS指定运行账户user-1

    要实现此功能,有两种办法:

    a) 在web.config文件中的<system.web>节点下,添加如下配置:<identity impersonate="true" userName="user-1" password="123456" />

    b) 在WEB项目中添加公用类LogonImpersonate

    public class LogonImpersonate : IDisposable

        {

     

            static public string DefaultDomain

            {

     

                get

                {

     

                    return ".";

     

                }

     

            }

     

            const int LOGON32_LOGON_INTERACTIVE = 2;

     

            const int LOGON32_PROVIDER_DEFAULT = 0;

     

            [System.Runtime.InteropServices.DllImport("Kernel32.dll")]

     

            extern static int FormatMessage(int flag, ref IntPtr source, int msgid, int langid, ref string buf, int size, ref IntPtr args);

     

            [System.Runtime.InteropServices.DllImport("Kernel32.dll")]

            extern static bool CloseHandle(IntPtr handle);

     

            [System.Runtime.InteropServices.DllImport("Advapi32.dll", SetLastError = true)]

     

            extern static bool LogonUser(

     

            string lpszUsername,

     

            string lpszDomain,

     

            string lpszPassword,

     

            int dwLogonType,

     

            int dwLogonProvider,

     

            ref IntPtr phToken

     

            );

     

            IntPtr token;

     

            System.Security.Principal.WindowsImpersonationContext context;

     

            public LogonImpersonate(string username, string password)

            {

     

                if (username.IndexOf("\\") == -1)

                {

     

                    Init(username, password, DefaultDomain);

     

                }

     

                else

                {

     

                    string[] pair = username.Split(new char[] { '\\' }, 2);

     

                    Init(pair[1], password, pair[0]);

     

                }

     

            }

     

            public LogonImpersonate(string username, string password, string domain)

            {

     

                Init(username, password, domain);

     

            }

     

            void Init(string username, string password, string domain)

            {

     

                if (LogonUser(username, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref token))

                {

     

                    bool error = true;

     

                    try

                    {

     

                     context = System.Security.Principal.WindowsIdentity.Impersonate(token);

     

                     error = false;

     

                    }

     

                    finally

                    {

     

                        if (error)

     

                            CloseHandle(token);

     

                    }

     

                }

                else

                {

     

                    int err = System.Runtime.InteropServices.Marshal.GetLastWin32Error();

     

     

     

                    IntPtr tempptr = IntPtr.Zero;

     

                    string msg = null;

     

     

     

                    FormatMessage(0x1300, ref tempptr, err, 0, ref msg, 255, ref tempptr);

     

     

     

                    throw (new Exception(msg));

     

                }

     

            }

     

            ~LogonImpersonate()

            {

     

                Dispose();

     

            }

     

            public void Dispose()

            {

     

                if (context != null)

                {

     

                    try

                    {

     

                        context.Undo();

     

                    }

     

                    finally

                    {

     

                        CloseHandle(token);

     

                        context = null;

     

                    }

     

                }

     

            }

     

        }

    }

    在访问映射磁盘之前首先调用此类为IIS更换运行用户:LogonImpersonate imper = new LogonImpersonate("administrator", "123.com");

    5、  在访问共享目录前,调用WNetHelper.WNetAddConnection,添加磁盘映射

       public static bool CreateDirectory(string path)

            {

     

                uint state = 0;

     

                if (!Directory.Exists("Z:"))

                {

     

                    state = WNetHelper.WNetAddConnection(@"administrator", "123.com", @"\\192.168.1.72\test$", "Z:");

     

                }

     

                if (state.Equals(0))

                {

     

                    Directory.CreateDirectory(path);

     

                    return true;

     

                }

     

                else

                {

     

                    throw new Exception("添加驱动器错误" + state.ToString());

     

                }

     

            }

    6、完成。

  • 相关阅读:
    对小课堂cpp的用户体验
    面试题 02.07. 链表相交 做题小结
    Leetcode 133. 克隆图 做题小结
    Leetcode 889. 根据前序和后序遍历构造二叉树-105. 从前序与中序遍历序列构造二叉树-106. 从中序与后序遍历序列构造二叉树
    图 的矩阵表示 和邻接表表示
    二叉树 常用函数 小结
    LeetCode 100. 相同的树 做题小结
    LeetCode 897. 递增顺序查找树 做题小结
    Leetcode 814. 二叉树剪枝 做题小结
    Leetcode l872. 叶子相似的树 做题小结
  • 原文地址:https://www.cnblogs.com/ptisagoodman/p/7755190.html
Copyright © 2011-2022 走看看