上传文件不起作用 – 需要帮助

我正在尝试使用WebBrowser控件上传文件(图像)。 似乎无法做到并需要一些帮助。

这是Html:

这是C#代码……

  elements = webBrowser.Document.GetElementsByTagName("input"); foreach (HtmlElement file in elements) { if (file.GetAttribute("name") == "file") { file.Focus(); file.InvokeMember("Click"); SendKeys.Send("C:\\Images\\CCPhotoID.jpg" + "{ENTER}"); } } 

请注意,文件上载按钮出现,但无法在文件名区域中输入任何文件名。

IMO,你正在尝试做的事实上是UI测试自动化的合法场景。 IIRC,在早期版本的IE中,可以使用文件名填充字段,而不显示“ Choose File对话框。 出于安全原因,这不再可能,因此您必须将密钥发送到对话框。

这里的问题是file.InvokeMember("Click")显示一个modal dialog,你想要将键发送到对话框,但是在对话框关闭执行SendKeys.Send (它是模态的,后跟所有) 。 您需要先打开对话框,然后发送密钥并将其关闭。

使用WinForms Timer可以解决这个问题,但我更喜欢使用async/awaitTask.Delay (工作代码):

 async Task PopulateInputFile(HtmlElement file) { file.Focus(); // delay the execution of SendKey to let the Choose File dialog show up var sendKeyTask = Task.Delay(500).ContinueWith((_) => { // this gets executed when the dialog is visible SendKeys.Send("C:\\Images\\CCPhotoID.jpg" + "{ENTER}"); }, TaskScheduler.FromCurrentSynchronizationContext()); file.InvokeMember("Click"); // this shows up the dialog await sendKeyTask; // delay continuation to let the Choose File dialog hide await Task.Delay(500); } async Task Populate() { var elements = webBrowser.Document.GetElementsByTagName("input"); foreach (HtmlElement file in elements) { if (file.GetAttribute("name") == "file") { file.Focus(); await PopulateInputFile(file); } } } 

IMO,这种方法对于UI自动化脚本非常方便。 您可以像这样调用Populate ,例如:

 void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { this.webBrowser.DocumentCompleted -= webBrowser_DocumentCompleted; Populate().ContinueWith((_) => { MessageBox.Show("Form populated!"); }, TaskScheduler.FromCurrentSynchronizationContext()); } 

就这么简单

  elements = webBrowser.Document.GetElementsByTagName("input"); foreach (HtmlElement file in elements) { if (file.GetAttribute("name") == "file") { SelectFile(); file.InvokeMember("Click"); } } 

制作此function并在点击之前调用它将完美地工作

  public async void SelectFile() { await Task.Delay(2000); SendKeys.Send("C:\\Images\\CCPhotoID.jpg" + "{ENTER}"); } 

我面临没有任何特征性错误看看我发布了这个问题