使用.net自动下载文件

时间:2015-07-10 12:24:13

标签: .net vb.net

我有要求我必须通过代码登录网站,然后通过导航到某个位置下载报告文件。我已成功登录并已到达文件下载的URL但无法自动将其保存到磁盘。 以下是我的代码

Imports SHDocVw
Imports mshtml
Imports System.Net

 Module Module1
Dim HTMLDoc As HTMLDocument
Dim MyBrowser As InternetExplorer
Sub Main()
    MyGmail()
End Sub
Sub MyGmail()

    Dim MyHTML_Element As IHTMLElement
    Dim MyURL As String
    On Error GoTo Err_Clear
    MyURL = "https://example.com/"
    MyBrowser = New InternetExplorer
    MyBrowser.Silent = True
    MyBrowser.Navigate(MyURL)
    MyBrowser.Visible = True
    Do
    Loop Until MyBrowser.ReadyState = tagREADYSTATE.READYSTATE_COMPLETE
    HTMLDoc = MyBrowser.Document
    HTMLDoc.all.txtUserID.Value = "xyz@example.com" 'Enter your email id here
    HTMLDoc.all.txtPassword.Value = "test123" 'Enter your password here

   For Each MyHTML_Element In HTMLDoc.getElementsByTagName("input")
        If MyHTML_Element.Type = "submit" Then MyHTML_Element.click() : Exit For
    Next

    'Navigate to reports folder
    Dim newReportURL As String
    newReportURL = "https://some_static_url_to_navigate"
    MyBrowser.Navigate(newReportURL)
    Dim i As Integer
    Dim reportURL As String
    reportURL = ""
    i = 0
    For Each MyHTML_Element In HTMLDoc.getElementsByTagName("a")
        If DirectCast(MyHTML_Element, mshtml.IHTMLAnchorElement).innerText = "Export" And i = 1 Then

            reportURL = DirectCast(MyHTML_Element, mshtml.IHTMLAnchorElement).href
        End If

        If DirectCast(MyHTML_Element, mshtml.IHTMLAnchorElement).innerText = "Export" Then
            i = i + 1
        End If


    Next

    MyBrowser.Navigate(reportURL)

    For Each MyHTML_Element In HTMLDoc.getElementsByTagName("input")
        If MyHTML_Element.Type = "submit" Then
            MyHTML_Element.click() : Exit For
        End If

    Next


    Dim xlsReportURL As String
    xlsReportURL = DirectCast(MyBrowser.Document, mshtml.IHTMLDocument).url


Err_Clear:
    If Err.Number <> 0 Then
        Err.Clear()
        Resume Next
    End If
End Sub
 End Module

最后一个变量 xlsReportURL 包含我的报告网址,格式为.xls。如何将此报告直接保存到我的硬盘上?

1 个答案:

答案 0 :(得分:1)

通过webclient有一个方法DownloadFile()。您应该尝试使用它而不是BrowserControl

请参阅Download a file through the WebBrowser control