C#通过用户名与密码访问共享目录

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices; namespace FileTools
{
public class NetworkShareConnect
{ #region WNetUseConnection枚举参数
//dwScope
const int RESOURCE_CONNECTED = 0x00000001;
const int RESOURCE_GLOBALNET = 0x00000002;
const int RESOURCE_REMEMBERED = 0x00000003; //dwType
const int RESOURCETYPE_ANY = 0x00000000;
const int RESOURCETYPE_DISK = 0x00000001;
const int RESOURCETYPE_PRINT = 0x00000002; //dwDisplayType
const int RESOURCEDISPLAYTYPE_GENERIC = 0x00000000;
const int RESOURCEDISPLAYTYPE_DOMAIN = 0x00000001;
const int RESOURCEDISPLAYTYPE_SERVER = 0x00000002;
const int RESOURCEDISPLAYTYPE_SHARE = 0x00000003;
const int RESOURCEDISPLAYTYPE_FILE = 0x00000004;
const int RESOURCEDISPLAYTYPE_GROUP = 0x00000005; //dwUsage
const int RESOURCEUSAGE_CONNECTABLE = 0x00000001;
const int RESOURCEUSAGE_CONTAINER = 0x00000002; //dwFlags
const int CONNECT_INTERACTIVE = 0x00000008;
const int CONNECT_PROMPT = 0x00000010;
const int CONNECT_REDIRECT = 0x00000080;
const int CONNECT_UPDATE_PROFILE = 0x00000001;
const int CONNECT_COMMANDLINE = 0x00000800;
const int CONNECT_CMD_SAVECRED = 0x00001000; const int CONNECT_LOCALDRIVE = 0x00000100;
#endregion #region Errors参数
const int NO_ERROR = ; const int ERROR_ACCESS_DENIED = ;
const int ERROR_ALREADY_ASSIGNED = ;
const int ERROR_BAD_DEVICE = ;
const int ERROR_BAD_NET_NAME = ;
const int ERROR_BAD_PROVIDER = ;
const int ERROR_CANCELLED = ;
const int ERROR_EXTENDED_ERROR = ;
const int ERROR_INVALID_ADDRESS = ;
const int ERROR_INVALID_PARAMETER = ;
const int ERROR_INVALID_PASSWORD = ;
const int ERROR_MORE_DATA = ;
const int ERROR_NO_MORE_ITEMS = ;
const int ERROR_NO_NET_OR_BAD_PATH = ;
const int ERROR_NO_NETWORK = ; const int ERROR_BAD_PROFILE = ;
const int ERROR_CANNOT_OPEN_PROFILE = ;
const int ERROR_DEVICE_IN_USE = ;
const int ERROR_NOT_CONNECTED = ;
const int ERROR_OPEN_FILES = ; private struct ErrorClass
{
//定义错误类结构体
public int num;
public string message;
public ErrorClass(int num, string message)
{
this.num = num;
this.message = message;
}
} //连接失败信息汇总
private static ErrorClass[] ERROR_LIST = new ErrorClass[] {
new ErrorClass(ERROR_ACCESS_DENIED, "Error: Access Denied"),
new ErrorClass(ERROR_ALREADY_ASSIGNED, "Error: Already Assigned"),
new ErrorClass(ERROR_BAD_DEVICE, "Error: Bad Device"),
new ErrorClass(ERROR_BAD_NET_NAME, "Error: Bad Net Name"),
new ErrorClass(ERROR_BAD_PROVIDER, "Error: Bad Provider"),
new ErrorClass(ERROR_CANCELLED, "Error: Cancelled"),
new ErrorClass(ERROR_EXTENDED_ERROR, "Error: Extended Error"),
new ErrorClass(ERROR_INVALID_ADDRESS, "Error: Invalid Address"),
new ErrorClass(ERROR_INVALID_PARAMETER, "Error: Invalid Parameter"),
new ErrorClass(ERROR_INVALID_PASSWORD, "Error: Invalid Password"),
new ErrorClass(ERROR_MORE_DATA, "Error: More Data"),
new ErrorClass(ERROR_NO_MORE_ITEMS, "Error: No More Items"),
new ErrorClass(ERROR_NO_NET_OR_BAD_PATH, "Error: No Net Or Bad Path"),
new ErrorClass(ERROR_NO_NETWORK, "Error: No Network"),
new ErrorClass(ERROR_BAD_PROFILE, "Error: Bad Profile"),
new ErrorClass(ERROR_CANNOT_OPEN_PROFILE, "Error: Cannot Open Profile"),
new ErrorClass(ERROR_DEVICE_IN_USE, "Error: Device In Use"),
new ErrorClass(ERROR_EXTENDED_ERROR, "Error: Extended Error"),
new ErrorClass(ERROR_NOT_CONNECTED, "Error: Not Connected"),
new ErrorClass(ERROR_OPEN_FILES, "Error: Open Files"),
}; private static string getErrorForNumber(int errNum)
{
//遍历获得错误代码
foreach (ErrorClass er in ERROR_LIST)
{
if (er.num == errNum) return er.message;
}
return "Error: Unknown, " + errNum;
}
#endregion //调用系统函数WNetUseConnection
//用于连接共享
[DllImport("Mpr.dll")]
private static extern int WNetUseConnection(
IntPtr hwndOwner,
NETRESOURCE lpNetResource,
string lpPassword,
string lpUserID,
int dwFlags,
string lpAccessName,
string lpBufferSize,
string lpResult
);
//用于删除连接
[DllImport("Mpr.dll")]
private static extern int WNetCancelConnection2(
string lpName,
int dwFlags,
bool fForce
); [StructLayout(LayoutKind.Sequential)]
private class NETRESOURCE
{
public int dwScope = ;
public int dwType = ;
public int dwDisplayType = ;
public int dwUsage = ;
public string lpLocalName = "";//映射到本地的盘符,如"Z:"。不做驱动器映射,可为空
public string lpRemoteName = "";//共享的网络路径
public string lpComment = "";
public string lpProvider = "";
} /// <summary>
/// 连接共享
/// </summary>
/// <param name="remoteUNC">共享网络路径</param>
/// <param name="username">登录用户名</param>
/// <param name="password">密码</param>
/// <returns></returns>
public static string connectToShare(string remoteUNC, string username, string password)
{
return connectToRemote(remoteUNC, username, password, false);
} /// <summary>
/// 没用户密码连接
/// </summary>
/// <param name="remoteUNC">共享网络路径</param>
/// <returns></returns>
public static string connectToShare(string remoteUNC)
{
return connectToRemote(remoteUNC, "", "", true);
} private static string connectToRemote(string remoteUNC, string username, string password, bool promptUser)
{
NETRESOURCE nr = new NETRESOURCE
{
dwType = RESOURCETYPE_DISK,
lpRemoteName = remoteUNC
}; int ret;
if (promptUser)
ret = WNetUseConnection(IntPtr.Zero, nr, "", "", CONNECT_INTERACTIVE | CONNECT_PROMPT, null, null, null);
else
ret = WNetUseConnection(IntPtr.Zero, nr, password, username, , null, null, null); if (ret == NO_ERROR) return null;
return getErrorForNumber(ret);
} public static string disconnectRemote(string remoteUNC)
{
int ret = WNetCancelConnection2(remoteUNC, CONNECT_UPDATE_PROFILE, false);
if (ret == NO_ERROR) return null;
return getErrorForNumber(ret);
} }
}

测试:

string _Server=this.txtServer.Text.Trim();
string _ID=this.txtID.Text.Trim();
string _Password=this.txtPassword.Text.Trim(); string _ConnMsg = NetworkShareConnect.connectToShare(_Server, _ID, _Password);
if (_ConnMsg == null)
{ this.myGroupBox_Green1.BackColor = Color.FromName("Green");
this.lblMessage.Text = "连接成功,正在上传文件至服务器...";
FileHelper.MoveFiles(this.txtPath.Text, _Server, true, true);
}
else
{
this.myGroupBox_Green1.BackColor = Color.FromName("Red");
this.lblMessage.Text = "错误:检测到无法连接至服务器."; this.timer1.Enabled = false;
this.btnStart.Enabled = true;
this.btnStart.Text = "Start";
}

C#通过用户名与密码访问共享目录的更多相关文章

  1. Windows Server 2008下共享资源访问走捷径 (不用用户名 和 密码 访问共享)

    1. 启用来宾帐号2. 共享目录添加“Guest”帐号3. “gpedit.msc”,打开对应系统的组策略编辑窗口;在该编辑窗口的左侧显示区域,依次展开“本地计算机策略”/“计算机配置”/“Windo ...

  2. 服务器资源共享--IIS站点/虚拟目录中访问共享目录(UNC)

    本文重点描述如何使用IIS访问共享资源来架设站点或执行 ASP.Net 等脚本. 通常情况下,拥有多台服务器的朋友在使用IIS建立站点的时候,会遇到如何把多台服务器的资源合并到一起的问题.如何让A服务 ...

  3. ubuntu下的Samba配置:使每个用户可以用自己的用户名和密码登录自己的home目录

    http://blog.csdn.net/fly_qj/article/details/21744797 1.先要安装Samba sudo apt-get install samba openssh- ...

  4. Apache:如何访问共享目录

    环境说明:Apache的版本是2.4.10,共享目录有两种情况,一种是windows server的目录共享,还有一种是linux的NAS.无论访问哪一种共享目录,都需要用户名和密码. 问题说明:如何 ...

  5. Windows 之 删除保存的共享凭据(用户名和密码)

    当我们在访问Windows共享文件夹或者NAS网络共享盘的时候,Windows会提示输入访问共享所需要的用户名和密码,如果我们勾选了“记住我的凭据”,Windows 就会将认证凭据保存到计算机中,以方 ...

  6. TortoiseGit:记住用户名和密码

    1.背景: 我们在使用 tortoisegit 工具时会无可避免的经常性 pull 和 push,这时通常要输入用户名和密码,由于麻烦,就有人提出了记住用户名和密码的需求... ... 2.设置: [ ...

  7. svn客户端重新设置用户名和密码

    在第一次使用TortoiseSVN从服务器CheckOut的时候,会要求输入用户名和密码,这时输入框下面有个选项是保存认证信息,如果选了这个选项,那么以后就不用每次都输入一遍用户名密码了. 不过,如果 ...

  8. TortoiseGit 连接oschina不用每次输入用户名和密码的方法

    每次git clone 和push 都要输入用户名和密码.虽然安全,但在本机上每次都输有些麻烦,如何记住用户名和密码呢? 在网上看了各种方法,太杂,很多可能环境不一样,一直行不通.最后找到一种有效的方 ...

  9. TortoiseSVN客户端重新设置用户名和密码

    TortoiseSVN客户端重新设置用户名和密码 在第一次使用TortoiseSVN从服务器CheckOut的时候,会要求输入用户名和密码,这时输入框下面有个选项是保存认证信息,如果选了这个选项,那么 ...

随机推荐

  1. .NET Framework 4 与.NET Framework 4 Client Profile有什么区别?

    .net framework 自从 2002 年发展至今,已经历了好几个版本,1.0, 1.1, 2.0, 3.0, 3.5 等不同的版本更替,.net framework 的Redistributa ...

  2. 2017-9-12-Linux移植&驱动开发

    准备学习Linux很长时间了,很大的一个原因就是兴趣,Linux对科技进步发展.人们生活的改变影响之深很难用简简单单的一些话描述清楚.跟Linux密切相关的东西,开源软件.c语言.底层驱动.网络.服务 ...

  3. [PA2014]Bazarek

    [PA2014]Bazarek 题目大意: 有\(n(n\le10^6)\)件商品,\(m(m\le10^6)\)次询问.每次询问若选出其中的\(k\)个,要求它们的总价为奇数,求最大可能的总价. 思 ...

  4. NIOH

    目录 NIOH中的双刀与阴阳术的应用 作战准备篇 2周目毕业装备: 加点: 双刀: 核心技能: 还行的技能: 被动技能: 忍术: 阴阳术: 必学: 选学: 守护灵: 隐世茶室 & 铁匠铺 出发 ...

  5. multiprocess模块

    什么是进程 什么是进程 进程是计算机中的程序关于某数据集合一次运行活动,是系统进行资源分配和调度的基本单位,是操作系统结构的基础,进程与进程之间数据隔离,执行过程异步 为什么会出现进程的概念 合理利用 ...

  6. python添加、修改、删除、访问类对象属性的2种方法

    1.直接添加.修改.删除.访问类对象属性 class Employee (object): empCount = 0 def __init__(self, name, salary) : self.n ...

  7. Stack的源码分析和应用实例

    1.Stack介绍 Stack是栈.它的特性是:先进后出(FILO:First In Last Out). java工具包中的Stack是继承于Vector(矢量队列)的,由于Vector是通过数组实 ...

  8. Sublime_分屏显示

  9. JS_高程3.基本概念(3)

    1.ECMAScript数值的范围 由于内存的限制,在大多数浏览器中,ECMAScript能够拿保存的数据的范围是 5e-324 ~ 1.7976931348623157e+308,其中最小的数值保存 ...

  10. 调用 LoadLibraryEx 失败,在 ISAPI 筛选器 "C:\Windows\Microsoft.NET\Framework\v4.0.30319\\aspnet_filter.dll" 上

    开始 -> 运行 -> inetmgr -> 应用程序池 -> 找到 我的网站对象的 程序池 -> 右键 -> 高级设置 -> 启用32位应用程序 由 fal ...