基本信息
源码名称:WebBrowser 模拟上传文件 实例
源码大小:0.01M
文件格式:.rar
开发语言:C#
更新时间:2013-04-19
   友情提示:(无需注册或充值,赞助后即可获取资源下载链接)

     嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):813200300

本次赞助数额为: 2 元 
   源码介绍

实现了模拟按键与选择文件等功能,详细实现见压缩包

对于IE7及以下,可以简单的利用SendKeys.SendWait方法设置input值,当然首先要将焦点集中在该控件上,利用HtmlElement的focus方法很容易做到。具体可以看后面的代码。但是对于IE8来说,它的安全性更高,具体参看文章http://blogs.msdn.com/ie/archive/2008/07/02/ie8-security-part-v-comprehensive-protection.aspx

对于IE8来说,file input只能模拟点击upload按钮,然后在弹出的对话框中输入文件名,然后点击确定。



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.IO;

namespace BatchShowMyCode
{
    public partial class Form1 : Form
    {
        private HtmlElement htmlForm, htmlUpload, htmlCode;
        //Uri url = new Uri("file:///D:/Apache2.2/htdocs/task/upload.html");    
        Uri url = new Uri("http://www.showmycode.com/");
        
        public Form1()
        {
            InitializeComponent();            
            this.webBrowser1.ScriptErrorsSuppressed = true;
            this.webBrowser1.Url = url;
            this.webBrowser1.DocumentCompleted  = new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
            //this.webBrowser1.FileDownload  = new EventHandler(webBrowser1_FileDownload);
        }

        private int fileNumber = 164;
        private string[] files = null;
        private int count = 104   1;
        String dir = "D:\\Apache2.2\\htdocs\\manage";
        private String[] GetAllFiles()
        {
            
            String ext = "*.php";
            List<string> fileList = new List<string>();
            List<string> dirList = new List<string>();
            dirList.Add(dir);
            for(int i=0; i<dirList.Count; i  )
            {
                fileList.AddRange(Directory.GetFileSystemEntries(dirList[i], ext));
                dirList.AddRange(Directory.GetDirectories(dirList[i]));
            }            
            return fileList.ToArray();
        }

        private String GetCurrentFile()
        {
            if (files == null)
            {
                files = GetAllFiles();
            }
            //if (fileNumber < files.Length && fileNumber < count)
            if (fileNumber < files.Length)
            {                
                return files[fileNumber];
            }
            return null;
            
        }

        void webBrowser1_FileDownload(object sender, EventArgs e)
        {
            //throw new NotImplementedException();
            log("---download----");
        }

        private int countOfCode = 0;    //连续两次upload之后需要reload,否则可能没有响应
        void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            try
            {
                UploadFile();
                if (GetCode())
                {
                    countOfCode = (countOfCode   1) % 2;
                    Thread.Sleep(10 * 1000);
                    if (countOfCode == 0)   //连续两次UploadFile之后调用Reload
                    {
                        Reload();
                    }
                    else
                    {
                        UploadFile();
                    }
                }
            }
            catch (Exception ex)
            {
                log(ex.Message);
                log(ex.StackTrace);
                throw ex;
            }
        }

        private bool GetCode()
        {
            //return false;
            if (GetCurrentFile() == null)
            {
                log("---decode all files !!!--------");
                return false;
            }
            htmlCode = this.webBrowser1.Document.GetElementById("output");

            if (htmlCode != null)
            {
                StringBuilder sb = new StringBuilder();
                foreach (HtmlElement li in htmlCode.FirstChild.GetElementsByTagName("LI"))
                {
                    //log(li.InnerText);
                    sb.AppendLine(li.InnerText);
                }
                SaveCode(files[fileNumber], sb.ToString());
                htmlForm = null;
                return true;
            }
            return false;
        }

        string targetDir = "D:\\phpcode";
        private void SaveCode(string file, string code)
        {
            file = file.Replace(dir, targetDir);

            log("Save code to ["   file   "]");
            CreateDirectory(file);
            using (StreamWriter writer = File.CreateText(file)) 
            {
                writer.Write(code);
                writer.Flush();
                fileNumber  ;
            }
        }

        private void CreateDirectory(string file)
        {
            DirectoryInfo d = Directory.GetParent(file);
            DirectoryInfo lastDir = d;
            if (!d.Exists)
            {
                while (!d.Exists)
                {
                    d = d.Parent;
                }
                d.CreateSubdirectory(lastDir.FullName.Substring(d.FullName.Length 1));
            }
        }

        private void UploadFile()
        {
            
            if (htmlForm != null) //第二次DocumentComplete
            {
                return;
            }           
            htmlForm = this.webBrowser1.Document.GetElementById("form");            
            if (htmlForm != null)
            {
                String file = GetCurrentFile();
                if (file == null)
                {
                    return;
                }
                htmlForm = htmlForm.FirstChild;
                log(String.Format("-----Begin Upload No={0} file={1}------", fileNumber, file));
                foreach (HtmlElement el in htmlForm.GetElementsByTagName("INPUT"))
                {
                    if (el.TagName.ToLower() == "input" && !String.IsNullOrEmpty(el.Name) && el.Name.ToLower() == "upload")
                    {
                        htmlUpload = el;
                        break;
                    }
                }
                if (htmlUpload == null)
                {
                    MessageBox.Show("Cannot find upload input control");
                    return;
                }
                try
                {
                    FillUploadControl(htmlUpload, file);
                    //log("set upload file value = "   file);
                    //log("input value = "   htmlUpload.GetAttribute("value"));
                    if (!String.IsNullOrEmpty(htmlUpload.GetAttribute("value")))
                    {
                        htmlForm.InvokeMember("submit");
                        log("---Submit Success------");
                        return;
                    }
                    log("---Submit Fail------["   file   "]");  
                }
                catch (Exception ex)
                {
                    log("-------Exception--------");
                    log(ex.StackTrace);
                }
            }
        }

        void FillUploadControl(HtmlElement htmlUpload, string file)
        {
            log(""   this.webBrowser1.Version.Major);

            if (this.webBrowser1.Version.Major >= 8)
            {
                htmlUpload.Focus();
                DelayFillFileChooseDialog(file);
                SendKeys.SendWait("{TAB}");
                SendKeys.SendWait(" ");
                Thread.Sleep(5 * 1000);
            }
            else 
            {
                int i = 50;
                while (true)
                {
                    htmlUpload.Focus();
                    SendKeys.SendWait(file);
                    log("----set value "   i   "th ----");
                    if (i-- < 0)
                        break;

                    if (String.IsNullOrEmpty(htmlUpload.GetAttribute("value")))
                    {
                        Thread.Sleep(100);
                    }
                    else
                    {
                        break;
                    }
                }
            }

        }

        void DelayFillFileChooseDialog(string file)
        {
            BackgroundWorker b = new BackgroundWorker();
            b.RunWorkerCompleted  = new RunWorkerCompletedEventHandler(b_RunWorkerCompleted);
            b.DoWork  = new DoWorkEventHandler(b_DoWork);
            b.RunWorkerAsync(file);
        }

        void b_DoWork(object sender, DoWorkEventArgs e)
        {
            Thread.Sleep(5000);
            e.Result = e.Argument;
        }
        
        void b_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {

            SendKeys.Send(e.Result as string);
            SendKeys.Send("{Enter}");
        }


        private void btnReload_Click(object sender, EventArgs e)
        {
            Reload();            
        }

        private void Reload()
        {
            log("-------Reload-----");
            //this.webBrowser1.Stop();
            htmlForm = null;
            this.webBrowser1.Navigate(url);
        }

        private void log(String str)
        {
            log(str, false);
        }

        private void log(string str, bool clean)
        {
            if (clean) 
            {
                txtlog.Clear();
            }
            txtlog.AppendText("["   DateTime.Now   "] "   str   "\n");            
        }

        private void button1_Click(object sender, EventArgs e)
        {
            htmlUpload.Focus();
            SendKeys.SendWait(GetCurrentFile());
            log("input value = "   htmlUpload.GetAttribute("value"));  
        }

        private void button2_Click(object sender, EventArgs e)
        {
            //htmlForm.InvokeMember("submit");
            foreach (String file in GetAllFiles())
                log(file);
        }



    }
}