打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
[转]访问共享文件夹(解决输入用户名密码问题)在.NET中的编程实现
概述
一般用户在访问局域网中的计算机时都需要提供访问凭据,如果想通过编程来实现自动登录,.NET开发人员一般首先会想到通过调用WMI来实现。但是在实现过程中也许你会发现使用ConnectionOptions类不是很理想,因此本文采用了平台调用的方式来介绍共享访问编程实现。
API介绍
mpr.dll是Windws操作系统网络通讯相关模块,通过对功能需求的分析,直接调用mpr.dll来实现该功能。在.NET中需要通过平台调用(platforminvoke)来调用其中的方法,这里需要用到mpr.dll中的两个方法。对于mpr.dll中包含的具体功能这里不进行阐述,大家通过MSDN可以找到详细说明,这里只列出方法定义。
DWORDWNetAddConnection2(
LPNETRESOURCE lpNetResource,
LPCTSTRlpPassword,
LPCTSTRlpUsername,
DWORDdwFlags
);
该方法主要功能是添加远程网络连接。
参数描述如下:
lpNetResource:是一个包含网络访问资源的结构,在这里作为参数用来指定详细的网络连接信息,具体请看下面。
lpPassword:指出访问远程计算机的密码。在Windows 95/98/Me系统中,该值必须设置为NULL或空字符串。
lpUsername:指出访问远程计算机的用户名。在Windows 95/98/Me系统中,该值必须设置为NULL或空字符串。
dwFlags:指出连接选项,包含六种设置,具体可以看MSDN。
方法返回值:如果方法执行成功返回“NO_ERROR”即“0”。如果执行失败返回System ErrorCode
NETRESOURCE结构通过多个字段指定网络连接资源信息。定义如下:
typedefstruct _NETRESOURCE {
DWORDdwScope;
DWORDdwType;
DWORDdwDisplayType;
DWORDdwUsage;
LPTSTRlpLocalName;
LPTSTRlpRemoteName;
LPTSTRlpComment;
LPTSTRlpProvider;
}NETRESOURCE;
各个成员描述如下:
dwScope:指定枚举范围。设置RESOURCE_CONNECTED,RESOURCE_GLOBALNET,RESOURCE_REMEMBERED三值之一。
dwType:指定访问的资源类型。设置三个值之一。RESOURCETYPE_ANY表示所有资源;RESOURCETYPE_DISK表示磁盘资源;RESOURCETYPE_PRINT表示打印机。
dwDisplayType:指出资源显示类型。RESOURCEDISPLAYTYPE_DOMAIN;RESOURCEDISPLAYTYPE_SERVER;RESOURCEDISPLAYTYPE_SHARE;RESOURCEDISPLAYTYPE_GENERIC。
dwUsage:描述资源的使用方式。设置RESOURCEUSAGE_CONNECTABLE或RESOURCEUSAGE_CONTAINER。
lpLocalName:同dwScope关联,指定本地映射。
lpRemoteName:远程访问文件夹路径。
lpComment:描述。
lpProvider:资源提供者,可以设置为NULL。
DWORDWNetCancelConnection2(
LPCTSTRlpName,
DWORDdwFlags,
BOOLfForce
);
通过该方法实现释放存在的网络连接。
各成员描述如下:
lpName:指定本地驱动器或远程共享资源
dwFlags:表示断开连接方式。设置 0或CONNECT_UPDATE_PROFILE。
fForce:如果当前正在使用远程资源,是否进行强制断开连接。如果设置FALSE,在有远程资源使用的情况下关闭连接操作将会失败。
方法返回值:如果方法执行成功返回“NO_ERROR”即“0”。如果执行失败返回System ErrorCode
针对以上两个方法,有些System ErrorCode返回值并不意味远程资源不可以访问。
例如:
ERROR_SESSION_CREDENTIAL_CONFLICT
1219
Multiple connections to a server or sharedresource by the same user, using more than one user name, are notallowed. Disconnect all previous connections to the server orshared resource and try again.
ERROR_REMOTE_SESSION_LIMIT_EXCEEDED
1220
Anattempt was made to establish a session to a network server, butthere are already too many sessions established to thatserver.
代码实现
为便于在.NET环境中使用,本文写了一个WNetConnectionHelper静态类,对这些方法进行包装。
P/Invoke需要引用System.Runtime.InteropServices命名空间。由于代码简短,下面给出完整实现代码。
public staticclass WNetConnectionHelper
{
[DllImport("mpr.dll", EntryPoint = "WNetAddConnection2")]
privatestatic extern uintWNetAddConnection2(NetResource lpNetResource,string lpPassword, string lpUsername, uint dwFlags);
[DllImport("Mpr.dll", EntryPoint = "WNetCancelConnection2"))]
privatestatic extern uintWNetCancelConnection2(stringlpName, uint dwFlags, bool fForce);
[StructLayout(LayoutKind.Sequential)]
publicclass NetResource
{
publicint dwScope;
publicint dwType;
publicint dwDisplayType;
publicint dwUsage;
publicstring lpLocalName;
publicstring lpRemoteName;
publicstring lpComment;
publicstring lpProvider;
}
publicstatic uint WNetAddConnection(NetResourcenetResource,stringusername,stringpassword)
{
uint result =WNetAddConnection2(netResource, password, username,0);
returnresult;
}
publicstatic uint WNetAddConnection(string username, string password, string remoteName, string localName)
{
NetResource netResource =new NetResource();
netResource.dwScope = 2; //RESOURCE_GLOBALNET
netResource.dwType = 1; //RESOURCETYPE_ANY
netResource.dwDisplayType = 3; //RESOURCEDISPLAYTYPE_GENERIC
netResource.dwUsage = 1; //RESOURCEUSAGE_CONNECTABLE
netResource.lpLocalName = localName;
netResource.lpRemoteName =remoteName.TrimEnd('//');
//netResource.lpRemoteName =lpComment;
//netResource.lpProvider = null;
uint result =WNetAddConnection2(netResource, password, username,0);
returnresult;
}
publicstatic uint WNetCancelConnection(string name,uint flags,bool force)
{
uint nret =WNetCancelConnection2(name, flags, force);
returnnret;
}
}
应用示例
最后,通过两个简单示例来演示WNetConnectionHelper类的使用
a.列举远程计算机共享文件夹资源。代码如下:
try
{
string result = WNetConnectionHelper.WNetAddConnection("TestAccout(用户名)","xxxxxx(密码)",@"\\192.168.1.10\test(共享地址)",null(或指定映射路径,如"y:"));
string []files = Directory.GetFiles(@"\\192.168.1.10\test\fw");
uint n =WNetConnectionHelper.WNetCancelConnection("//192.120.40.10//test(或"y:")",1, true); //取消映射
}
catch (Exception ex)
{
//编写异常处理代码
}
b.另一个比较常见的应用是在ASP.NET服务器端访问其他计算机的资源,比如文档服务器,然后通过Web页面输出。
主要示例代码如下:
protected voidPage_Load(object sender,EventArgse)
{
uint r =WNetConnectionHelper.WNetAddConnection("192.120.40.10//username","password", @"//192.120.40.10/test","Z:");
string filename= @"//192.120.40.10/test/fw/1.doc";
ReadFile(filename);
}
写文件到Web输出:
public voidReadFile(stringfilename)
{
Response.Clear();
Response.Charset = "utf-8";
Response.Buffer = true;
this.EnableViewState = false;
Response.ContentType = "application/ms-word";
Response.ContentEncoding =System.Text.Encoding.UTF8;
Response.AppendHeader("Content-Disposition", "inline;filename=1.doc");
try
{
Response.WriteFile(filename, true);
}
catch(Exceptionex)
{
Response.Write(ex.ToString());
}
Response.Flush();
}
以上方法对于大文件使用Response.WriteFile方法会有些问题,在实际编程中需要做优化处理。
结束语

本文中的有些功能描述可能不够具体或妥当,如果需要了解mpr.dll的更多功能还是建议看MSDN文档。对于WNetConnectionHelper的实现存在一些需要完善的地方,不过对于一般的应用基本可以满足,在实际使用时还需要考虑多线程的情况。另外,在有同名驱动器映射的情况下需要做一些判断,而且弄清楚SystemError Code的含义对代码的调试及正确执行有很大的帮助。This is some sampletext. You are usingFCKeditor.

第二种方法是通过:cmd->net use 输入一次用户名和密码后,客户端访问共享文件就不用再输入密码 命令:“net use\\192.168.39.178 "admin" /user:"admin"”
using System.Diagnostics;


Process prc = new Process();
prc.StartInfo.FileName = @ "cmd.exe ";
prc.StartInfo.UseShellExecute = false;
prc.StartInfo.RedirectStandardInput = true;
prc.StartInfo.RedirectStandardOutput = true;
prc.StartInfo.RedirectStandardError = true;
prc.StartInfo.CreateNoWindow = false;

prc.Start();
string cmd = @ "net use z: \\192.168.1.1\tmp ""pass""/user:""name""";
//"pass"连接服务器的密码 user:"name"用户名
//Process.Start( "net ",@"use z: \\192.168.1.1\tmp " "pass " " /user: " "name " "");
prc.StandardInput.WriteLine(cmd);

prc.StandardInput.Close();
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
call a DLL function with variable RT-parameter dynamically?
在C#里面调用带有回调函数和自定义结构体的DLL的例程
驱动程序安装类(C#)
C# IniFile用法
C#实现启用、禁用本地网络的三种方式
如何取电脑的:机器名、用户名、IP地址、MAC地址
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服