将文件复制到我无权访问的网络共享

时间:2012-07-11 03:17:21

标签: c# security impersonation file-copying

这是this问题

的扩展

我正在尝试将文件从本地用户的临时文件夹复制到远程文件共享。 我无法访问远程文件共享,因此我必须冒充用户。

现在,我可以从远程服务器成功读取文件并在本地复制它,但是我无法将本地文件写入共享,因为它给了我错误:

  

LOCAL文件的访问被拒绝

(因为我现在冒充其他用户)。

如果您需要一些代码我可以发布。

1 个答案:

答案 0 :(得分:12)

管理找到答案,

我只需要在模拟远程用户之前为本地文件创建FileStream,然后将FileStream传递给复制功能。

修改: 所以这是我的整个文件复制例程

using System.Security.Principal;
using System.Security.Permissions;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.IO;

public class ImpersonatedFileCopy : IDisposable
{
    #region Assembly Functions
    [DllImport("advapi32.dll")]
    public static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);

    [DllImport("kernel32.dll")]
    public static extern bool CloseHandle(IntPtr handle);
    #endregion

    #region Private Variables
    private IntPtr _TokenHandle = new IntPtr(0);
    private WindowsImpersonationContext _WindowsImpersonationContext;
    #endregion

    #region Constructors
    public ImpersonatedFileCopy(string domain, string username, string password)
    {
        Impersonate(domain, username, password);
    }
    #endregion

    #region Methods
    [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
    private void Impersonate(string domain, string username, string password)
    {
        bool returnValue;

        try
        {
            const int LOGON32_PROVIDER_DEFAULT = 0;
            const int LOGON32_LOGON_INTERACTIVE = 2;

            _TokenHandle = IntPtr.Zero;

            //Call LogonUser to obtain a handle to an access token.
            returnValue = LogonUser(username, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref _TokenHandle);
            if (returnValue)
            {
                WindowsIdentity newId = new WindowsIdentity(_TokenHandle);
                _WindowsImpersonationContext = newId.Impersonate();
            }
        }
        catch (Exception ex)
        {
            UndoImpersonate();
            Debug.Writeline("Error"+ex.Message);
        }
    }

    private void UndoImpersonate()
    {
        if (_WindowsImpersonationContext != null)
        {
            _WindowsImpersonationContext.Undo();
            if (!_TokenHandle.Equals(IntPtr.Zero))
            {
                CloseHandle(_TokenHandle);
            }
        }
    }

    public bool PutFile(FileStream source, string destRemoteFilename, bool overwrite)
    {
        try
        {
            if (!Directory.Exists(Path.GetDirectoryName(destRemoteFilename))) Directory.CreateDirectory(Path.GetDirectoryName(destRemoteFilename));
            using (FileStream dest = File.OpenWrite(destRemoteFilename))
            {
               source.Seek(0, SeekOrigin.Begin);
               source.CopyTo(dest);
            }
            return true;
        }
        catch
        {
            return false;
        }
    }

    public bool GetFile(string sourceRemoteFilename, FileStream dest, bool overwrite)
    {
        try
        {
            using (FileStream source = File.OpenRead(sourceRemoteFilename))
            {
                source.Seek(0, SeekOrigin.Begin);
                source.CopyTo(dest);
            }
            return true;
        }
        catch
        {
            return false;
        }
    }
    #endregion

    #region IDisposable
    public void Dispose()
    {
        UndoImpersonate();
        GC.SuppressFinalize(this);
    }
    #endregion
}

用法:

using (FileStream dest = File.OpenWrite(localDestinationFilename))
using (copy = new ImpersonatedFileCopy(domain,user,pass))
{
   success = copy.GetFile(remoteSourceFilename, dest, true);
}