Copy files over network via file share, user authentication

寵の児 提交于 2019-11-30 06:57:33

VB but easily translated to C#. Do this before your copy:

Private Sub Open_Remote_Connection(ByVal strComputer As String, ByVal strUserName As String, ByVal strPassword As String)
    Dim ProcessStartInfo As New System.Diagnostics.ProcessStartInfo
    ProcessStartInfo.FileName = "net"
    ProcessStartInfo.Arguments = "use \\" & strComputer & "\c$ /USER:" & strUsername & " " & strPassword
    ProcessStartInfo.WindowStyle = ProcessWindowStyle.Hidden
    System.Diagnostics.Process.Start(ProcessStartInfo)
    System.Threading.Thread.Sleep(2000)
End Sub

If you want to authenticate to a remote computer in order to move a file, you can use the LogonUser function to and WindowsIdentity to impersonate your user.

/// <summary>
/// Exécute une fonction en empruntant les credentials
/// </summary>
private T ApplyCredentials<T>(Func<T> func)
{
    IntPtr token;

    if (!LogonUser(
        _credentials.UserName,
        _credentials.Domain,
        _credentials.Password,
        LOGON32_LOGON_INTERACTIVE,
        LOGON32_PROVIDER_DEFAULT,
        out token))
    {
        Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
    }

    try
    {
        // On doit être impersonifié seulement le temps d'ouvrir le handle.
        using (var identity = new WindowsIdentity(token))
        using (var context = identity.Impersonate())
        {
            return func();
        }
    }
    finally
    {
        CloseHandle(token);
    }
}

// ...

if (_credentials != null)
{
    return this.ApplyCredentials(() => File.Open(path, mode, access, share));
}

return File.Open(path, mode, access, share);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!