C#
一种面向对象的类型安全的编程语言,它起源于 C 语言系列,包括对面向组件的编程的支持。
197 个问题
我正在尝试使用来自另一台机器B的凭据“machineA\user”访问共享文件夹“\machineA\shared”。不幸的是,machineA 不在 machineB 的域中。我怎样才能通过c#访问共享文件夹....
尝试使用此代码不起作用
NetworkCredential theNetworkCredential = new NetworkCredential(equipment.User, equipment.Password);
CredentialCache theNetCache = new CredentialCache();
theNetCache.Add(new Uri(equipment.SourceFolder), "Basic", theNetworkCredential);
string[] theFiles1 = Directory.GetFiles(equipment.SourceFolder);
Note:此问题总结整理于: Access a shared folder using the shared machine's local credential
由于 machineA 不在 machineB 的域中,因此您可以使用mpr.dll添加远程网络连接。 下面是一个你可能需要的示例:
public static class WNetConnectionHelper
{
[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;
}
public static uint WNetAddConnection(NetResource netResource, string username, string password)
{
uint result = WNetAddConnection2(netResource, password, username, 0);
return result;
}
public static uint WNetAddConnection(string username, string password, string remoteName, string localName)
{
NetResource netResource = new NetResource();
netResource.dwScope = 2; //RESOURCE_GLOBALNET
netResource.dwType = 1; //RESOURCETYPE_ANY
netResource.dwDisplayType = 3; //RESOURCEDISPLAYTYPE_GENERIC
netResource.dwUsage = 1; //RESOURCEUSAGE_CONNECTABLE
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;
}
}
这是另一种可能有帮助的解决方案。
如果答案有帮助,请点击“接受答案”并点赞。 注意:如果您想接收此线程的相关电子邮件通知,请按照我们文档中的步骤启用电子邮件通知。