zoukankan      html  css  js  c++  java
  • 从本地复制文件到其他域的服务器 File.Copy

      最近有个需求,需要部署代码到多台服务器上面,而本地是无法直接访问服务器的,只能通过开了80端口的网站访问,因此,在服务器上面部署了一个上传文件的服务,该服务需要复制上传后的文件到其他服务器上面,如果直接使用System.IO.File.Copy方法,会提示用户名或密码失败,因为当前上下文的凭据是应用程序池所用的凭据;

    解决方法是先模拟登录,再使用System.IO.File.Copy方法,以下是核心代码:

    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Data;
    using System.Diagnostics;
    using System.Runtime.InteropServices;
    using System.Security.Principal;
    using System.Security.Permissions;
    
    public class Form1
    {
        [DllImport("advapi32.DLL", SetLastError = true)]
        public static extern int LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
        private void Button1_Click(System.Object sender, System.EventArgs e)
        {
            IntPtr admin_token = default(IntPtr);
            WindowsIdentity wid_current = WindowsIdentity.GetCurrent();
            WindowsIdentity wid_admin = null;
            WindowsImpersonationContext wic = null;
            try {
                MessageBox.Show("Copying file...");
                if (LogonUser("Remote Admin name", "Remote Domain name", "Remote User Password", 9, 0, ref admin_token) != 0) {
                    wid_admin = new WindowsIdentity(admin_token);
                    wic = wid_admin.Impersonate();
                    System.IO.File.Copy("C:\right.bmp", "\\xxx.xxx.xxx.xxx\testnew\right.bmp", true);
                    MessageBox.Show("Copy succeeded");
                } else {
                    MessageBox.Show("Copy Failed");
                }
            } catch (System.Exception se) {
                int ret = Marshal.GetLastWin32Error();
                MessageBox.Show(ret.ToString(), "Error code: " + ret.ToString());
                MessageBox.Show(se.Message);
            } finally {
                if (wic != null) {
                    wic.Undo();
                }
            }
        }
    }

    以上参考来源于https://stackoverflow.com/questions/13132926/how-to-copy-folder-from-one-server-to-another-with-different-domain-using-c-shar

  • 相关阅读:
    C#Redis哈希Hashes
    C#Redis集合set
    C#Redis列表List
    C#Redis字符串
    入门redis
    C#/Net代码精简优化技巧
    单点登录在asp.net中的简单实现
    sql注入
    数据库sql优化
    常常忘记但是很重要的sql语句
  • 原文地址:https://www.cnblogs.com/tcli/p/11236343.html
Copyright © 2011-2022 走看看