關於在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());
}
}