映射网络驱动器(共享路经)

调用WINDOWS API函数实现映射网络驱动器

 

首先引入命名空间:

using System.Runtime.InteropServices;

 

映射对象:

 

代码
[StructLayout(LayoutKind.Sequential)]
    
public class NetResource
    {
        
public int dwScope;
        
public int dwType;
        
public int dwDisplayType;
        
public int dwUsage;
        
public string LocalName;
        
public string RemoteName;
        
public string Comment;
        
public string provider;
    }

    
public class Pathing
    {
        [DllImport(
"mpr.dll", CharSet = CharSet.Ansi)]
        
private static extern int WNetAddConnection2(NetResource netResource, string password, string username, int flag);

        [DllImport(
"mpr.dll",CharSet=CharSet.Ansi)]
        
private static extern int WNetCancelConnection2(string lpname, int flag, bool force);

        
/// <summary>
        
/// 映射网络驱动器
        
/// </summary>
        
/// <param name="localName">本地盘符</param>
        
/// <param name="remotePath">远程路经 如\\\\172.18.118.106\\f</param>
        
/// <param name="userName">远程服务器用户名</param>
        
/// <param name="password">远程服务器密码</param>
        
/// <returns>true映射成功,false映射失败</returns>
        public static bool WNetAddConnection2(string localName,string remotePath,string userName,string password)
        {
            NetResource netResource 
= new NetResource();    
            netResource.dwScope 
= 2;
            netResource.dwType 
= 0x1;
            netResource.dwDisplayType 
= 3;
            netResource.dwUsage 
= 1;
            netResource.LocalName 
= localName;
            netResource.RemoteName 
= remotePath;
            netResource.provider 
= null;
            
int ret = WNetAddConnection2(netResource, password, userName, 0);
            
if (ret == 0)
                
return true;
            
return false;
        }

        
/// <summary>
        
/// 断开网路驱动器
        
/// </summary>
        
/// <param name="lpName">映射的盘符</param>
        
/// <param name="flag">true时如果打开映射盘文件夹,也会断开,返回成功 false时打开映射盘文件夹,返回失败</param>
        
/// <returns></returns>
        public static bool WNetCancelConnection2(string lpName,bool flag)
        {
            
int ret = WNetCancelConnection2(lpName, 0, flag);
            
if (ret == 0)
                
return true;
            
return false;
        }
    }

 

 

posted @ 2010-04-21 12:53  nyzfl  阅读(589)  评论(1编辑  收藏  举报