[英]Use C# to save a file in a folder or shared folder in a remote machine. The remote machine is in another domain
我在域 A 上托管了一個 C# api。此 api 接收文件作為表單數據(我使用 HttpContext.Current.Request.Files 提取文件)。 在這個 api 中,我需要實現一種方法,將提取的文件保存到另一個域中的遠程計算機的文件夾或共享文件夾中,例如域 B(我的公司域)。 我有在域 B 中運行的機器的訪問憑據。
我正在使用 VS2015 進行開發。 我的目標框架是 .NET 4.5.2。 我嘗試使用 WNetUseConnection(Mpr.dll) 方法進行連接。 使用這種方法,當從與遠程計算機相同的域連接時,我能夠成功連接並保存文件。 但是當我試圖從外部域 B(遠程機器的域)連接時,我無法這樣做。 我收到錯誤 53。我研究了這個錯誤,發現它是“找不到網絡路徑”。
我覺得我需要我能得到的所有幫助。 需要在 2 天內完成此操作。
下面給出的是我連接到域 B 中的遠程機器的函數調用。
RemoteConnect.connectToRemote("\\xxx.xxx.xxx.xxx\C$", @"domain-B\username", "password");
我在下面給出了連接類 (RemoteConnect.cs) 中用於使用 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 = 0;
public int dwType = 0;
public int dwDisplayType = 0;
public int dwUsage = 0;
public string lpLocalName = "";
public string lpRemoteName = "";
public string lpComment = "";
public string lpProvider = "";
}
public static string connectToRemote(string remoteUNC, string username, string password)
{
return connectToRemote(remoteUNC, username, password, false);
}
public static string connectToRemote(string remoteUNC, string username, string password, bool promptUser)
{
NETRESOURCE nr = new NETRESOURCE();
nr.dwType = RESOURCETYPE_DISK;
nr.lpRemoteName = remoteUNC;
// nr.lpLocalName = "F:";
int ret;
if (promptUser)
ret = WNetUseConnection(IntPtr.Zero, nr, "", "", CONNECT_INTERACTIVE | CONNECT_PROMPT, null, null, null);
else
ret = WNetUseConnection(IntPtr.Zero, nr, password, username, 0, 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);
}
您是否嘗試過 NetworkCredential? 也許我想得太簡單了,我不明白你的問題..
這一直適用於我的需要:
NetworkCredential networkCredential = new NetworkCredential("username", "password", "domainname");
CredentialCache credentialCache = new CredentialCache();
credentialCache.Add(new Uri(@"\\networkshare\"), "Basic", networkCredential);
//Proceed with whatever file-io you need using the normal .NET file io. Example:
string[] folders = System.IO.Directory.GetDirectories(@"\\networkshare\Users\Userimages");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.