欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

c# 执行windows模拟登录

程序员文章站 2024-02-01 17:32:34
1.登录代码 2.执行登录 ......

1.登录代码

    /// <summary>
        /// 登录权限
        /// </summary>
        /// <param name="path"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
          public  bool connectstate(string path, string username, string password)
        {
            bool flag = false;
            process proc = new process();
            try
            {
                proc.startinfo.filename = "cmd.exe";
                proc.startinfo.useshellexecute = false;
                proc.startinfo.redirectstandardinput = true;
                proc.startinfo.redirectstandardoutput = true;
                proc.startinfo.redirectstandarderror = true;
                proc.startinfo.createnowindow = true;
                proc.start();
                string dosline = "net use " + path + " " + password + " /user:" + username;
                proc.standardinput.writeline(dosline);
                proc.standardinput.writeline("exit");
                while (!proc.hasexited)
                {
                    proc.waitforexit(1000);
                }
                string errormsg = proc.standarderror.readtoend();
                proc.standarderror.close();
                if (string.isnullorempty(errormsg))
                {
                    flag = true;
                }
                else
                {
                    throw new exception(errormsg);
                }
            }
            catch (exception ex)
            {
              displaylistboxmsg(ex.message);
            }
            finally
            {
                proc.close();
                proc.dispose();
            }
            return flag;
        }

2.执行登录

 private void 登录_click(object sender, eventargs e)
        {
             bool userbool = connectstate(@"\\**.**.*.*",user.text,pwd.text);
           if (userbool)
           {
                displaylistboxmsg("登录成功:"+user.text);
           }
           else
           {
                displaylistboxmsg("登录失败");
           }
        }