如何使用 mshtml 以编程方式从 ac# windows 应用程序写入网页中文件类型的输入字段?
我有 c# windows 应用程序项目,必须打开 IE,导航到网站,登录,然后上传一些文件。
我使用 shDocvW 和 mshtml 库来执行此操作。我可以打开 IE,导航到网站并登录,但无法上传文件。
我可以导航到该网站,然后使用 -
HTMLInputElement txtbox1 =(HTMLInputElement)oDoc.all.item("login", 0);
txtbox1.value = "Login_name";
我也可以类似地向输入字段 添加文本值(这是“文本”类型的输入字段)类型为“密码”。登录网站后,我必须上传文件。
我面临的问题是我无法将路径(字符串)添加到“文件”类型的输入字段。
我无法找到任何解决方案。
I have a c# windows app project which has to open IE, navigate to a website, login and then upload a few files.
I used shDocvW and mshtml libraries to do this. I am able to open IE, navigate to the website and login but am not able to upload the files.
I am able to navigate to the website and then add a text value to the input fields(This is an input field of type "text") on the website using -
HTMLInputElement txtbox1 =(HTMLInputElement)oDoc.all.item("login", 0);
txtbox1.value = "Login_name";
I also was similarly able to even add a text value to the input field of type "password". After I logged in to the website, I have to upload a file.
The problem I am facing is that I am not able to add the path(a string) to the input field of type "file".
I am not able to find any solutions.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我尝试了很多方法来做到这一点,但这是不可能的,因为 IE8 出于安全原因将 Value 属性设置为只读。
好吧,我确实找到了解决办法。它非常简单,但使用
SendKeys
并不总是被认为是最好的编程解决方案。但是,它确实完成了工作。通过检查活动窗口并可能在每个
SendKeys
命令之前设置正确的窗口,可以改进此代码。这可以通过使用user32.dll
的FindWindow()
和FindWindowEx()
来完成。 Windows API 中的这些方法用于查找活动窗口和子窗口。I tried many ways to do this but it was not possible because IE8 made the Value property of read-only for security reasons.
Well, I did find a work around. It is very simple but the use of
SendKeys
is not always considered the best programming solution. But, it does the job.This code can be bettered by checking for the active window and perhaps setting the correct one before every
SendKeys
command. This can be done by using theFindWindow()
andFindWindowEx()
ofuser32.dll
. These methods in the windows API are used to find the active window and the child windows.您的实施是否必须涉及使用 IE?使用
WebClient
类通过 POST 请求上传文件可能会更简单,但这确实取决于表单是否提供任何其他上传操作。如果没有,您可以使用WebClient.UploadFile
。如果您需要为此表单上传多个 POST 值(即新文件名?),请查看此处:同一调用中的 WebClient.UploadFile 和 WebClient.UploadValues
Does your implementation have to involve using IE? This may be simpler using the
WebClient
class to upload the file using a POST request, but this does depend on if the form provides any other post actions with the upload. If not, you can useWebClient.UploadFile
.If you need to upload multiple POST values for this form (i.e. new file name?), have a look here: WebClient.UploadFile and WebClient.UploadValues in the same call