Copy files over network via file share, user authentication

后端 未结 2 1382
执笔经年
执笔经年 2020-12-30 08:37

I am building a .net C# console program to deploy file to a windows file share server (folder that is being shared). The path is :: \\\\192.168.0.76\\htdocs\\public

2条回答
  •  青春惊慌失措
    2020-12-30 09:13

    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.

    /// 
    /// Exécute une fonction en empruntant les credentials
    /// 
    private T ApplyCredentials(Func 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);
    

提交回复
热议问题