C# 跨UNC复制文件
我有一个服务器a,它托管一个应用程序,将文件写入其硬盘。我还有另外两台服务器B和C。A上的UNC共享可以访问B和C 我希望写入A上硬盘的任何文件都能以类似的目录结构复制到服务器B和C。我曾尝试使用File.Copy,但每次都会被拒绝访问。我该如何设置安全系统才能让它正常工作?或者有没有办法模拟用户C# 跨UNC复制文件,c#,copy,unc,C#,Copy,Unc,我有一个服务器a,它托管一个应用程序,将文件写入其硬盘。我还有另外两台服务器B和C。A上的UNC共享可以访问B和C 我希望写入A上硬盘的任何文件都能以类似的目录结构复制到服务器B和C。我曾尝试使用File.Copy,但每次都会被拒绝访问。我该如何设置安全系统才能让它正常工作?或者有没有办法模拟用户 谢谢我不会试图在C#中解决这个问题。现在已经有很多文件复制产品,包括为Windows Server 2003和更高版本内置的产品。我不会尝试对安全性进行编程以支持这一点。您最好使用Windows来配置
谢谢我不会试图在C#中解决这个问题。现在已经有很多文件复制产品,包括为Windows Server 2003和更高版本内置的产品。我不会尝试对安全性进行编程以支持这一点。您最好使用Windows来配置它(假设您使用的是Windows服务器)。您必须确保为服务器B和C分配了允许服务器A写入UNC共享的权限
此时,假设这是Windows,您可以为服务器B和C的计算机名分配权限,也可以将服务器B和C放入一个组中,并在服务器a上为该组分配权限。如果您只是尝试访问需要凭据的网络共享,您可以执行以下操作:
...
using (new NetworkImpersonationContext("domain", "username", "password"))
{
// access network here
}
...
public class NetworkImpersonationContext : IDisposable
{
private readonly WindowsIdentity _identity;
private readonly WindowsImpersonationContext _impersonationContext;
private readonly IntPtr _token;
private bool _disposed;
public NetworkImpersonationContext(string domain, string userName, string password)
{
if (!LogonUser(userName, domain, password, 9, 0, out _token))
throw new Win32Exception();
_identity = new WindowsIdentity(_token);
try
{
_impersonationContext = _identity.Impersonate();
}
catch
{
_identity.Dispose();
throw;
}
}
#region IDisposable Members
public void Dispose()
{
GC.SuppressFinalize(this);
Dispose(true);
}
#endregion
[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);
protected virtual void Dispose(bool disposing)
{
if (_disposed)
return;
_disposed = true;
if (disposing)
{
_impersonationContext.Dispose();
_identity.Dispose();
}
if (!CloseHandle(_token))
throw new Win32Exception();
}
~NetworkImpersonationContext()
{
Dispose(false);
}
}
可能重复:编辑:错误的问题标记为重复,但它显示了如何模拟的答案。我不明白为什么这个问题被关闭为离题。关于访问UNC共享时如何使用网络凭据进行身份验证,这是一个非常有效的问题。我在下面给出了一个优雅的答案。