weixin_43902841
2019-07-03 14:51 阅读 540

C#客户端使用LogonUser访问服务器上的共享文件,提示用户名或密码错误(客户端与服务器在同一域中)

 private static bool IfUpdate()
        {
            bool bRtn = true;
            try
            {
                string AppDataPath = System.Windows.Forms.Application.StartupPath;//程序根目录
                //从服务器copy文件
                //System.IO.File.Copy(@"\\dev-server\D\csv.csv", @"D:\TEST.txt", true);

                IntPtr admin_token = default(IntPtr);
                WindowsIdentity wid_admin = null;
                WindowsImpersonationContext wic = null;

                string struser = global::InventoryApplication.Properties.Settings.Default.User;//用户名
                string strpwd = global::InventoryApplication.Properties.Settings.Default.Pwd;//密码
                string strIP = global::InventoryApplication.Properties.Settings.Default.URL; //服务器IP
                string strurl = global::InventoryApplication.Properties.Settings.Default.Route;//共享目录路径

                //在程序中模拟域帐户登录  
                if (LogonUser(struser, strIP, strpwd, 9, 0, ref admin_token) != 0)
                {
                    using (wid_admin = new WindowsIdentity(admin_token))
                    {
                        using (wic = wid_admin.Impersonate())
                        {
                            //假定要操作的文件路径是  
                            FileInfo file = new FileInfo(@"\\" + strIP + "\\" + strurl + "\\" + COMMON.ClsCommon.strUpdatetxt + "");

                            string strFILE = AppDataPath + COMMON.ClsCommon.strUpdatetxt + "";
                            if (File.Exists(strFILE))
                            {
                                File.Delete(strFILE);
                            }

                            //copy版本号
                            file.CopyTo(AppDataPath + COMMON.ClsCommon.strUpdatetxt + "");

                        }
                    }
                }
                else
                {
                    COMMON.ClsCommon.ErrorMassage("连接失败");
                }
            }
            catch (Exception ee)
            {
                COMMON.ClsCommon.ErrorMassage(ee.Message);
                bRtn = false;
            }
            return bRtn;
        }

        [DllImport("advapi32.DLL", SetLastError = true)]
        public static extern int LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

相关推荐