当连接到当前用户(在我的情况下,支持网络的服务用户)没有权限的网络共享时,必须提供名称和密码.
我知道如何使用Win32函数(WNet*来自的家族mpr.dll),但是想用.Net(2.0)功能.
有哪些选择?
也许更多信息有助于:
是否有某种方法可以作为本地(非网络)用户进行身份验证,以便在.Net中通过网络复制文件?
net use不是一个选项,我似乎无法让LogonUser工作.
有任何想法吗?
[编辑]这是一些代码:
public class UserImpersonator : IDisposable
{
private WindowsImpersonationContext _impersonationContext;
private IntPtr _userHandle = IntPtr.Zero;
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool LogonUser(
string lpszUsername,
string lpszDomain,
string lpszPassword,
int dwLogonType,
int dwLogonProvider,
out IntPtr phToken
);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool CloseHandle(IntPtr hHandle);
public UserImpersonator(string username, string password)
{
LogonUser(username, "", password, (int)LogonType.LOGON32_LOGON_NETWORK,
(int)LogonProvider.LOGON32_PROVIDER_DEFAULT, out _userHandle);
_impersonationContext = WindowsIdentity.Impersonate(_userHandle);
}
public void Dispose()
{
CloseHandle(_userHandle);
_impersonationContext.Undo();
} …Run Code Online (Sandbox Code Playgroud) 我试图将文件从本地驱动器复制到服务器上的文件夹之一.服务器上文件夹的名称是"DBFiles".除了用户名'user'和密码'password1'之外,没有人可以访问此内容!
在处理文件之前,如果不存在则创建目录.
有人可以在创建目录'Test'时帮助获取访问权限,然后复制文件.
if (!Directory.Exists(@"\\server-a\copiedfiles\"))
Directory.CreateDirectory(@"\\server-a\DBFiles\"+Test);
File.Copy("C:\Temp\abc.txt", @"\\server-a\DBFiles\");
Run Code Online (Sandbox Code Playgroud)
这是c#中的原始代码.
NetworkShare.DisconnectFromShare(@"\\server-a\DBFiles", true); //Disconnect in case we are currently connected with our credentials;
NetworkShare.ConnectToShare(@"\\server-a\DBFiles", "user1", "password1!"); //Connect with the new credentials
File.Copy(@"c:\temp\T1.txt", @"\\server-a\DBFiles\T1.txt");
NetworkShare.DisconnectFromShare(@"\\server-a\DBFiles", false); //Disconnect from the server.
Run Code Online (Sandbox Code Playgroud)
它因拒绝访问而给出错误.
如何在c#中以编程方式执行网络登录,访问共享驱动程序?尝试通过资源管理器或net use shell命令打开共享可以实现同样的目的.