2011年11月11日 星期五

[C#] UNC 網路芳鄰連接 含帳號密碼 [使用WindowsIdentity方法]

之前有寫過 UNC 連接,但是是採用 CMD 模式 請見

[C#] UNC 網路芳鄰連接 含帳號密碼


這一次因為是要在 IIS 上執行,所以改採用 WindowsIdentity 來作業.

按我下載 SourceCode

//首先
using System.Security.Permissions;
using System.Runtime.InteropServices;
using System.Security.Principal;

//追加 namespace 上方
[assembly: SecurityPermissionAttribute(SecurityAction.RequestMinimum, UnmanagedCode = true)]
[assembly: PermissionSetAttribute(SecurityAction.RequestMinimum, Name = "FullTrust")]

//Dll
        [DllImport("advapi32.dll", SetLastError = true)]
        public static extern bool LogonUser(
           string lpszUsername,
           string lpszDomain,
           string lpszPassword,
           int dwLogonType,
           int dwLogonProvider,
           ref IntPtr phToken);
      
        [DllImport("kernel32.dll")]
        public extern static bool CloseHandle(IntPtr hToken);


  public class Connect_Net
    {
        public string Server_IP
        {
            get;
            set;
        }
        public string UserNmae
        {
            get;
            set;
        }
        public string Password
        {
            get;
            set;
        }
    }



         private void button1_Click(object sender, EventArgs e)
        {
            Connect_Net z = new Connect_Net();
            z.UserNmae = "ftpuser";
            z.Password= "ftpuser";
            z.Server_IP = "172.23.108.157";

            string IPath = @"\\" + z.Server_IP + @"\ftp";
            const int LOGON32_PROVIDER_DEFAULT = 0;
            const int LOGON32_LOGON_NEW_CREDENTIALS = 9;
            IntPtr tokenHandle = new IntPtr(0);
            tokenHandle = IntPtr.Zero;
            bool returnValue = LogonUser(z.UserNmae, z.Server_IP, z.Password,
            LOGON32_LOGON_NEW_CREDENTIALS,
            LOGON32_PROVIDER_DEFAULT,
            ref tokenHandle);
            WindowsIdentity w = new WindowsIdentity(tokenHandle);
            System.Security.Principal.WindowsImpersonationContext kk =  w.Impersonate();
            if (false == returnValue)
            {
                return;
            }
        
            DirectoryInfo dir = new DirectoryInfo(IPath);
            FileInfo[] inf = dir.GetFiles();
            for (int i = 0; i < inf.Length; i++)
            {
                Console.WriteLine(inf[i].Name);
                //檔案取回
                System.IO.File.Copy("\\\\"+z.Server_IP+"\\ftp\\"+inf[i].Name, "C:\\"+inf[i].Name+".jpg");
            }
            kk.Undo();
        }

沒有留言:

張貼留言