我有一个服务器A,它托管一个应用程序,将文件写入它的硬盘驱动器。我还有另外两台服务器B和C。A上的UNC共享可以访问B和C。
我希望将任何写入A硬盘的文件都复制到与服务器B和C类似的目录结构中。我尝试过使用File.Copy,但每次都会拒绝访问。我该如何设置安全才能让它正常工作呢?或者有没有一种方法可以模拟用户?
谢谢
发布于 2013-03-01 05:29:16
如果您只是尝试访问需要凭据的网络共享,则可以执行以下操作:
我创建了一个实现此行为的可处理类。
...
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);
}
}发布于 2013-03-01 03:58:43
我不会尝试用C#来解决这个问题。市面上已经有了许多文件复制产品,包括为Windows Server2003及更高版本内置的DFS Replication。
发布于 2013-03-01 03:59:26
我不会尝试编写安全程序来支持这一点。最好的方法是使用Windows进行配置(假设您使用的是Windows服务器)。您必须确保服务器B和C具有分配的权限,以允许服务器A写入UNC共享。
此时,假设这是Windows,您可以将权限分配给服务器B和C的计算机名称,也可以将服务器B和C放入一个组中,然后将权限分配给服务器A上的该组。
https://stackoverflow.com/questions/15144469
复制相似问题