Friday, March 25, 2011

Function to download the file from the webpage and store it in location drive

Script:

msgbox SaveWebBinary ("www.al-islam.org/encyclopedia/shia5b.txt", "C:\a\sample.txt")

public Function SaveWebBinary(strUrl, strFile)
Const adTypeBinary = 1
Const adSaveCreateOverWrite = 2
Const ForWriting = 2
Dim web, varByteArray, strData, strBuffer, lngCounter, ado
Err.Clear
Set web = Nothing
Set web = CreateObject("WinHttp.WinHttpRequest.5.1")
If web Is Nothing Then
Set web = CreateObject("WinHttp.WinHttpRequest")
End if
If web Is Nothing Then
Set web = CreateObject("MSXML2.ServerXMLHTTP")
End if
If web Is Nothing Then
Set web = CreateObject("Microsoft.XMLHTTP")
End if
web.Open "GET", strURL, False
web.Send
If Err.Number <> 0 Then
SaveWebBinary = False
Set web = Nothing
Exit Function
End If
If web.Status <> "200" Then
SaveWebBinary = False
Set web = Nothing
Exit Function
End If
varByteArray = web.ResponseBody
Set web = Nothing

'Save the file
On Error Resume Next
Set ado = Nothing
Set ado = CreateObject("ADODB.Stream")
If ado Is Nothing Then
Set fs = CreateObject("Scripting.FileSystemObject")
Set ts = fs.OpenTextFile(strFile, ForWriting, True)
strData = ""
strBuffer = ""
For lngCounter = 0 to UBound(varByteArray)
ts.Write Chr(255 And Ascb(Midb(varByteArray,lngCounter + 1, 1)))
Next
ts.Close
Else
ado.Type = adTypeBinary
ado.Open
ado.Write varByteArray
ado.SaveToFile strFile, adSaveCreateOverWrite
ado.Close
End If
SaveWebBinary = True
Set ado = Nothing
Set ts = Nothing
Set fs = Nothing
End Function

No comments: