您需要获取映射到 R: Drive 的网络地址,然后您可以将其用作代码中的文件/文件夹路径:
由于您需要密码才能访问此共享驱动器中的文件,因此您有两个选项,如 SO answer 中所述
1:设置AppPool用户
执行此操作的“正确”方法是将网络服务器的 AppPool 作为
可以访问共享的身份。这样,唯一的凭证
存储在 IIS 配置中安全地完成(而不是在您的代码中)
或在可读的配置文件中)。将网络服务器和文件服务器放入
相同的 Windows 域(或具有信任的不同域)是
最简单的方法,但是“相同的用户名/密码”应该在那里工作
也是。
2: P/Invoke 到 WNetAddConnection2
这里有一个很好的实现How To Access Network Drive Using C#
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Net;
public class ConnectToSharedFolder: IDisposable
{
readonly string _networkName;
public ConnectToSharedFolder(string networkName, NetworkCredential credentials)
{
_networkName = networkName;
var netResource = new NetResource
{
Scope = ResourceScope.GlobalNetwork,
ResourceType = ResourceType.Disk,
DisplayType = ResourceDisplaytype.Share,
RemoteName = networkName
};
var userName = string.IsNullOrEmpty(credentials.Domain)
? credentials.UserName
: string.Format(@"{0}\{1}", credentials.Domain, credentials.UserName);
var result = WNetAddConnection2(
netResource,
credentials.Password,
userName,
0);
if (result != 0)
{
throw new Win32Exception(result, "Error connecting to remote share");
}
}
~ConnectToSharedFolder()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
WNetCancelConnection2(_networkName, 0, true);
}
[DllImport("mpr.dll")]
private static extern int WNetAddConnection2(NetResource netResource,
string password, string username, int flags);
[DllImport("mpr.dll")]
private static extern int WNetCancelConnection2(string name, int flags,
bool force);
[StructLayout(LayoutKind.Sequential)]
public class NetResource
{
public ResourceScope Scope;
public ResourceType ResourceType;
public ResourceDisplaytype DisplayType;
public int Usage;
public string LocalName;
public string RemoteName;
public string Comment;
public string Provider;
}
public enum ResourceScope : int
{
Connected = 1,
GlobalNetwork,
Remembered,
Recent,
Context
};
public enum ResourceType : int
{
Any = 0,
Disk = 1,
Print = 2,
Reserved = 8,
}
public enum ResourceDisplaytype : int
{
Generic = 0x0,
Domain = 0x01,
Server = 0x02,
Share = 0x03,
File = 0x04,
Group = 0x05,
Network = 0x06,
Root = 0x07,
Shareadmin = 0x08,
Directory = 0x09,
Tree = 0x0a,
Ndscontainer = 0x0b
}
}
public string networkPath = @"\\{Your IP or Folder Name of Network}\Shared Data";
NetworkCredential credentials = new NetworkCredential(@"{User Name}", "{Password}");
public string myNetworkPath = string.Empty;
public byte[] DownloadFileByte(string DownloadURL)
{
byte[] fileBytes = null;
using (new ConnectToSharedFolder(networkPath, credentials))
{
var fileList = Directory.GetDirectories(networkPath);
foreach (var item in fileList) { if (item.Contains("ClientDocuments")) { myNetworkPath = item; } }
myNetworkPath = myNetworkPath + DownloadURL;
try
{
fileBytes = File.ReadAllBytes(myNetworkPath);
}
catch (Exception ex)
{
string Message = ex.Message.ToString();
}
}
return fileBytes;
}