ASP.NET访问网络驱动器(映射磁盘)
也许很多朋友在做WEB项目的时候都会碰到这样一个需求:
当用户上传文件时,需要将上传的文件保存到另外一台专门的文件服务器。
要实现这样一个功能,有两种解决方案:
方案一、在文件服务器上新建一站点,用来接收上传的文件,然后保存。
方案二、将文件服务器的指定目录共享给WEB服务器,用来保存文件。
方案一不用多说,应该是很简单的了,将上传文件的FORM表单的ACTION属性指向文件服务器上的站点即可,我们来重点说下方案二。
也许你会说,其实方案二也很简单,在WEB服务器上做下磁盘映射,然后直接访问不就行了。其实不是这样的,IIS默认账户为NETWORK_SERVICE,该账户是没权限访问共享目录的,所以当你把站点部署到IIS上的时候,再访问映射磁盘就会报“找不到路径”的错误。所以,直接创建磁盘映射是行不通的,我们需要在程序中用指定账户创建映射,并用该账户运行IIS进程,下面来说下详细步骤及相关代码。
1、在文件服务器上创建共享目录,并新建访问账户。
比如共享目录为:\\192.168.0.9\share
访问账户为:user-1 密码为:123456
2、在WEB服务器上新建用户:user-1 密码为:123456,用户组选择默认的user组即可。
3、在WEB项目中新建公共类WNetHelper
- using System.Runtime.InteropServices;
- 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("user-1", "123456");
5、在访问共享目录前,调用WNetHelper.WNetAddConnection,添加磁盘映射
- public static bool CreateDirectory(string path)
- {
- uint state = 0;
- if (!Directory.Exists("Z:"))
- {
- state = WNetHelper.WNetAddConnection(@"comp-1\user-1", "123456", @"\\192.168.0.9\share", "Z:");
- }
- if (state.Equals(0))
- {
- Directory.CreateDirectory(path);
- return true;
- }
- else
- {
- throw new Exception("添加网络驱动器错误,错误号:" + state.ToString());
- }
- }
6、完成。
简洁代码就是:
LogonImpersonate imper = new LogonImpersonate("user-1", "123456");
WNetHelper.WNetAddConnection(@"comp-1\user-1", "123456", @"\\192.168.0.9\share", "Z:");
Directory.CreateDirectory(@"Z:\newfolder");
file1.SaveAs(@"Z:\newfolder\test.jpg");
ASP.NET访问网络驱动器(映射磁盘)的更多相关文章
- ASP.NET访问网络映射盘&实现文件上传读取功能
最近在改Web的时候,遇到一个问题,要跨机器访问共享文件夹,以实现文件正常上传下载功能. 要实现该功能,可以采用HTTP的方式,也可以使用网络映射磁盘的方式,今天主要给大家分享一下使用网络映射磁盘的方 ...
- VBS映射网络驱动器 映射网络驱动器
Dim objNetwork Set objNetwork = CreateObject("Wscript.Network") if objNetwork.EnumNetworkD ...
- iis访问网络路径映射问题(UNC share)
最近在做一个功能,涉及到nas网络磁盘文件的保存和访问,在服务器上将对应的路径映射为Z盘,结果在iis上部署网站直接访问该路径,报无法找到该路径的错误. 用的是.net core开发,在vs直接启动程 ...
- IIS虚拟目录实现与文件服务器网络驱动器映射共享
这篇文章转载别人,想原创作者致敬! 我本人也遇到同样的问题,故转载记录. 本文重点描述如何使用IIS访问共享资源来架设站点或执行 ASP.Net 等脚本. 通常情况下,拥有多台服务器的朋友在使用IIS ...
- 转:IIS虚拟目录实现与文件服务器网络驱动器映射共享
这篇文章转载别人,想原创作者致敬! 我本人也遇到同样的问题,故转载记录. 本文重点描述如何使用IIS访问共享资源来架设站点或执行 ASP.Net 等脚本. 通常情况下,拥有多台服务器的朋友在使用IIS ...
- IIS下访问网络驱动器(网络位置)
System.Diagnostics.Process p = new System.Diagnostics.Process(); p.StartInfo.FileName = "cmd.ex ...
- asp.net访问网络路径方法(模拟用户登录)
public class IdentityScope : IDisposable { // obtains user token [DllImport("advapi32.dll" ...
- IIS/ASP.NET访问共享文件夹的可用方式
[截止2014-10-14] 网上搜索了很多篇文章,所提及的总共有两种方式: 1.Asp.Net模拟登陆: 例如: 实战ASP.NET访问共享文件夹(含详细操作步骤) 实现一个2008serve的II ...
- 关于windows service不能访问网络共享盘(NetWork Drive)的解决方案
我映射一个网络驱动器到本机的时候,发现本机的程序直接能访问读取网络驱动器,但是把本机的程序作为本机的windows服务运行的时候就不能访问了. Qt中的QDir::exist(folder)访问失败. ...
随机推荐
- Vue动态组件&异步组件
在动态组件上使用keep-alive 我们之前曾经在一个多标签的界面中使用is特性来切换不同的组件: Vue.js的动态组件模板 <component v-bind:is="curre ...
- 【codeforces 766E】Mahmoud and a xor trip
[题目链接]:http://codeforces.com/contest/766/problem/E [题意] 定义树上任意两点之间的距离为这条简单路径上经过的点; 那些点上的权值的所有异或; 求任意 ...
- Android第三方开源下拉框:NiceSpinner
Android第三方开源下拉框:NiceSpinner Android原生的下拉框Spinner基本上可以满足Android开发对于下拉选项的设计需求,但现在越来越流行的下拉框不满足于Andro ...
- Ubuntu镜像包版本差异
自接触Linux以来,一直使用ubuntu,下载ubuntu镜像的过程中,一个问题一直困扰我--desktop版镜像和server版镜像究竟有什么区别?难道就GUI有无的区别? 今天尝试解答这个问题. ...
- springCloud学习-服务的注册与发现(Eureka)
1.小记 这段时间有空,把springcloud的知识整理一下,好记性不如烂笔头,也让自己对springcloud有个清晰的认识.此次的整理记录主要借鉴了这位大佬的博客 https://blog.cs ...
- supervisord进程管理工具小结
前言 昨天临近下班,发现业务队列处理不及时,正好想到不久之前,上了一个新功能:通过队列异步转发微信消息.可能是消息太多了处理不过来,没怎么多想,处理不过来了,多增加处理进程就可以了,后来发现自己so ...
- OpenCV+iOS开发使用文档
一. 前言 OpenCV是开源的跨平台的计算机视觉库,实现了图像处理.计算机视觉和机器学习的很多通用算法. 对于移动设备没有快速输入的键盘,大的屏幕,其优势在于图像和声音,因此要 ...
- Android: Could not find com.android.support:support-v4:21.0.0
安装Android Support Repository即可解决这个问题.
- POJ 2947-Widget Factory(高斯消元解同余方程式)
题目地址:id=2947">POJ 2947 题意:N种物品.M条记录,接写来M行,每行有K.Start,End,表述从星期Start到星期End,做了K件物品.接下来的K个数为物品的 ...
- Google Code Jam在线測试题目--Alien Language
Problem After years of study, scientists at Google Labs have discovered an alien language transmitte ...