从Web下载多个文件

时间:2017-08-25 15:12:06

标签: vb.net

我正在开发一些应用程序,以便从网址下载不同日期的股票价格文件。我使用以下代码

Conn = New OdbcConnection("DSN=RA;MultipleActiveResultSets=True")
    If Conn.State = ConnectionState.Closed Then
        Conn.Open()
    End If
    Dim mont As Date
    mont = DateTimePicker1.Value
    Dim dnldurlA As String = "http://www.nseindia.com/content/historical/EQUITIES/"
    Dim dnldurlB As String = UCase(mont.ToString("MMM"))
    Dim dnldurlC As String = "/"
    Dim dnldurlD As String = "cm"
    Dim dnldurlE As String = mont.ToString("dd")
    Dim dnldurlF As String = mont.ToString("yyyy")
    Dim dnldurlG As String = "bhav"
    Dim dnldurlH As String = ".csv"
    Dim dnldurlI As String = ".zip"
    Dim dnldurlJ As String = "\"
    Dim FileName As String = dnldurlE & dnldurlB & dnldurlF & ".ZIP"
    Try
        Dim downloadClient As New WebClient()
        downloadClient.Headers("Accept") = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
        downloadClient.Headers("User-Agent") = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.83 Safari/537.1"
        Dim dnldurl As String = dnldurlA & dnldurlF & dnldurlC & dnldurlB & dnldurlC & dnldurlD & dnldurlE & dnldurlB & dnldurlF & dnldurlG & dnldurlH & dnldurlI
        downloadClient.DownloadFile(New Uri(dnldurl), ("C:\" & FileName))
        While (downloadClient.IsBusy = True)

        End While
        downloadClient.Dispose()
    Catch ex As Exception
        MsgBox("File can not be downloaded!!!")
        Me.Close()
    End Try

我在下载第一个文件后感到困惑,当我选择该文件为另一个日期时,它会抛出错误 {“远程服务器返回错误:(403)禁止。”} 但是当我退出应用程序并再次尝试相同的日期时,文件会立即下载。

请帮忙

提前致谢 克里斯

1 个答案:

答案 0 :(得分:0)

我做了一个小小的改动而且效果很好

Conn = New OdbcConnection("DSN=RA;MultipleActiveResultSets=True")
    If Conn.State = ConnectionState.Closed Then
        Conn.Open()
    End If
    Dim mont As Date
    mont = DateTimePicker1.Value
    Dim dnldurlA As String = "http://www.nseindia.com/content/historical/EQUITIES/"
    Dim dnldurlB As String = UCase(mont.ToString("MMM"))
    Dim dnldurlC As String = "/"
    Dim dnldurlD As String = "cm"
    Dim dnldurlE As String = mont.ToString("dd")
    Dim dnldurlF As String = mont.ToString("yyyy")
    Dim dnldurlG As String = "bhav"
    Dim dnldurlH As String = ".csv"
    Dim dnldurlI As String = ".zip"
    Dim dnldurlJ As String = "\"
    Dim FileName As String = dnldurlE & dnldurlB & dnldurlF & ".ZIP"
    Try
       Dim downloadClient As New WebClient()
       Dim dnldurl As String = dnldurlA & dnldurlF & dnldurlC & dnldurlB & dnldurlC & dnldurlD & dnldurlE & dnldurlB & dnldurlF & dnldurlG & dnldurlH & dnldurlI
       downloadClient.DownloadFile(New Uri(dnldurl), ("C:\" & FileName))
       While (downloadClient.IsBusy = True)

        End While
        downloadClient.Dispose()
    Catch ex As Exception
        MsgBox("File can not be downloaded!!!")
        Me.Close()
    End Try

由于