SQLの窓 イラストAC フリー素材

2015年01月11日

VB.net : Win32 API でHTTPダウンロード / バッチビルドキット付き

バソコンに %windir%\Microsoft.NET\Framework\v4.0.30319\vbc.exe があれば、exe をビルドできます



Win32 API 的には、URLDownloadToFile を使用するだけです。経験から言って、Framework を使用するよりは堅実なような気もします。
Imports System.IO	' Path
Imports System.Diagnostics	' Process
Imports System.Runtime.InteropServices	' DllImport

Module MyModule

<DllImport("urlmon.dll", CharSet:=CharSet.Unicode)> _
Private Function URLDownloadToFile( _
  ByVal pCaller As Integer, _
  ByVal szURL As String, _
  ByVal szFileName As String, _
  ByVal dwReserved As Integer, _
  ByVal lpfnCB As Integer _
) As Integer
End Function

' ********************************************************
' Win32 API でHTTPダウンロード
' 引数 : URL "ローカルパス" [s]
' s は省略可能で、指定するとダウンロード後にエクスプローラ
' を開きません
' (引数の例)
' http://lightbox.on.coocan.jp/download/WinOfSql102.zip .\WinOfSql102.zip
' ********************************************************
Sub Main()

	' 文字列の配列
	Dim argv As String()

	' コマンドラインの取得
	argv = System.Environment.GetCommandLineArgs()

	Dim ret As Integer
	Dim str As String

	' 引数が二つ以上の場合
	If argv.Length >= 3 Then
		' API の呼び出し
		ret = URLDownloadToFile( 0, argv(1), argv(2), 0, 0 )
		if ret = 0 then
			str = Path.GetFullPath( argv(2) )
			str = Path.GetDirectoryName( str )
			if argv.Length = 4 then
				if  argv(3) = "s" then
				else
					' 第3引数に s を指定しない場合は
					'  エクスプローラを開く
					Process.Start("explorer.exe","/e,"+str)
				end if
			else
				' 第3引数に s を指定しない場合は]
				' エクスプローラを開く
				Process.Start("explorer.exe","/e,"+str)
			end if
		end if
	end if

End Sub

End Module

' 古い vb の定義
' Private Declare Function URLDownloadToFile Lib "urlmon" Alias _
' "URLDownloadToFileA" (ByVal pCaller As Long, ByVal szURL As String, ByVal _
' szFileName As String, ByVal dwReserved As Long, ByVal lpfnCB As Long) As Long
' ▼
' http://support.microsoft.com/kb/244757/ja

このコードでは、ダウンロードした後、エクスプローラでダウンロードしたフォルダを開きます。


関連する記事


【VB.netの最新記事】
posted by at 2015-01-11 20:34 | VB.net | このブログの読者になる | 更新情報をチェックする