关于在web情况下访问C#客户端,导致C#客户端无法访问网络映射盘问题
关于问题是这样的,之前在做一个项目,需要通过java网页按钮,调用服务器上的C#客户端(exe文件),C#代码中有访问网络映射盘的路径假设为X盘,因此在服务器上直接启动exe文件是没问题;如果通过网页按钮来调取exe文件时会导致exe无法访问映射盘路径,要解决这个问题需要新增C#代码,即新增实现网络驱动盘共享代码;之前也在网上找到了相关代码,但是使用细节上说的不够详细,现在整理下分享出来,虽然使用情况不多,但是遇到这问题了还是比较纠结的难缠的。
1、新建C#控制台项目
2、新建LogonImpersonate.cs类
using System;
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;
}
}
}
}
3、新建WNetHelper.cs类
using System.Runtime.InteropServices;
using System.IO;
using System;
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、实现驱动映射,注意别看判断没用,但是必须地加上,否则访问不了网络驱动盘。
static void Main(string[] args)
{
//===========`加载网路映射盘代码,当通过web调用次应用程序时需要以下代码,否则访问路径失败===================
uint state = 0;
if (!Directory.Exists("Z:"))
{
//WNetHelper.WNetAddConnection(@"计算机名称\登录账户", "登录密码", @"映射路径", @"映射盘符名称");
state = WNetHelper.WNetAddConnection(@"CQQXYJS\yjsnyygyjs", "yjsnyygyjs27", @"\\192.168.1.110\micaps", @"Z:");
}
if (state.Equals(0))
{
}
else
{
Console.WriteLine("添加网络驱动器错误,错误号:" + state.ToString());
}
}