C#通过用户名与密码访问共享目录
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#通过用户名与密码访问共享目录的更多相关文章
- Windows Server 2008下共享资源访问走捷径 (不用用户名 和 密码 访问共享)
1. 启用来宾帐号2. 共享目录添加“Guest”帐号3. “gpedit.msc”,打开对应系统的组策略编辑窗口;在该编辑窗口的左侧显示区域,依次展开“本地计算机策略”/“计算机配置”/“Windo ...
- 服务器资源共享--IIS站点/虚拟目录中访问共享目录(UNC)
本文重点描述如何使用IIS访问共享资源来架设站点或执行 ASP.Net 等脚本. 通常情况下,拥有多台服务器的朋友在使用IIS建立站点的时候,会遇到如何把多台服务器的资源合并到一起的问题.如何让A服务 ...
- ubuntu下的Samba配置:使每个用户可以用自己的用户名和密码登录自己的home目录
http://blog.csdn.net/fly_qj/article/details/21744797 1.先要安装Samba sudo apt-get install samba openssh- ...
- Apache:如何访问共享目录
环境说明:Apache的版本是2.4.10,共享目录有两种情况,一种是windows server的目录共享,还有一种是linux的NAS.无论访问哪一种共享目录,都需要用户名和密码. 问题说明:如何 ...
- Windows 之 删除保存的共享凭据(用户名和密码)
当我们在访问Windows共享文件夹或者NAS网络共享盘的时候,Windows会提示输入访问共享所需要的用户名和密码,如果我们勾选了“记住我的凭据”,Windows 就会将认证凭据保存到计算机中,以方 ...
- TortoiseGit:记住用户名和密码
1.背景: 我们在使用 tortoisegit 工具时会无可避免的经常性 pull 和 push,这时通常要输入用户名和密码,由于麻烦,就有人提出了记住用户名和密码的需求... ... 2.设置: [ ...
- svn客户端重新设置用户名和密码
在第一次使用TortoiseSVN从服务器CheckOut的时候,会要求输入用户名和密码,这时输入框下面有个选项是保存认证信息,如果选了这个选项,那么以后就不用每次都输入一遍用户名密码了. 不过,如果 ...
- TortoiseGit 连接oschina不用每次输入用户名和密码的方法
每次git clone 和push 都要输入用户名和密码.虽然安全,但在本机上每次都输有些麻烦,如何记住用户名和密码呢? 在网上看了各种方法,太杂,很多可能环境不一样,一直行不通.最后找到一种有效的方 ...
- TortoiseSVN客户端重新设置用户名和密码
TortoiseSVN客户端重新设置用户名和密码 在第一次使用TortoiseSVN从服务器CheckOut的时候,会要求输入用户名和密码,这时输入框下面有个选项是保存认证信息,如果选了这个选项,那么 ...
随机推荐
- C#调用WebApi
1.WebRequest方式 Post: private void button1_Click(object sender, EventArgs e) { string ss= HttpPost(&q ...
- IntelliJ IDEA使用教程(简介)
最智能的IDE IDEA 全称IntelliJ IDEA 是java语言开发的集成环境,IntelliJ在业界被公认为最好的java开发工具之一,尤其在智能代码助手.代码自动提示.重构.J2EE支 ...
- 你真的了解META-INF吗?
你真的了解META-INF吗? 做过JAVA EE开发的工程师应该都知道在JAVA build出来的JAR或者WAR的顶层目录下有个META-INF文件夹吧,可是有多少人能够清楚说出这个文件夹到底是做 ...
- 【DWM1000】 code 解密8一 TAG接收blink response 信号
在分析这个部分前,目前我看到DWM1000 的资料,data可以分为blink和一般无线数据,后面有内容我们再扩充, 上面我们已经看到接收到blink触发的事件为 case SIG_RX_BLINK ...
- meta中minimal-ui属性
<meta id="viewport" name="viewport" content="width=device-width, user-sc ...
- PAT Basic 1002
1002 写出这个数 (20 分) 读入一个正整数 n,计算其各位数字之和,用汉语拼音写出和的每一位数字. 输入格式: 每个测试输入包含 1 个测试用例,即给出自然数 n 的值.这里保证 n 小于 1 ...
- HashMap源码分析和应用实例的介绍
1.HashMap介绍 HashMap 是一个散列表,它存储的内容是键值对(key-value)映射.HashMap 继承于AbstractMap,实现了Map.Cloneable.java.io.S ...
- 小甲鱼Python第十三讲课后题--014字符串
字符串的方法及注释 capitalize() 把字符串的第一个字符改为大写 casefold() 把整个字符串的所有字符改为小写 center(width) ...
- SpringMVC中使用JSON
前台发送: 传递JSON对象 function requestJson(){ $.ajax.({ type : "post", url : "${pageContext. ...
- poj2385 Apple Catching(dp状态转移方程推导)
https://vjudge.net/problem/POJ-2385 猛刷简单dp的第一天的第一题. 状态:dp[i][j]表示第i秒移动j次所得的最大苹果数.关键要想到移动j次,根据j的奇偶判断人 ...