Imports System
Imports System.IO
Imports System.Net
Imports System.Text.RegularExpressions
Class DownloadWithNoName
Shared Sub main(ByVal args As String())
If args.Length = 0 Then
Return
End If
Dim url As String = args(0)
Dim req As HttpWebRequest _
= CType(WebRequest.Create(url), HttpWebRequest)
Dim res As HttpWebResponse _
= CType(req.GetResponse(), HttpWebResponse)
Dim fileName As String = "download.tmp"
' ヘッダ情報からファイル名の取得
Dim dispos As String = res.Headers("Content-Disposition")
If Not String.IsNullOrEmpty(dispos) Then
' filename=<ファイル名>の抜き出し
Dim re As New Regex( _
"filename\s*=\s* " & _
"(?: " & _
" ""(?<filename>[^""]*)"" " & _
" | " & _
" (?<filename>[^;]*) " & _
") " _
, RegexOptions.IgnoreCase _
Or RegexOptions.IgnorePatternWhitespace)
Dim m As Match = re.Match(dispos)
If m.Success Then
fileName = m.Groups("filename").Value
End If
End If
' ファイルのダウンロード
Using st As Stream = res.GetResponseStream()
Using fs As New FileStream(fileName, FileMode.Create)
Dim buf(1024) As Byte
Dim count As Integer = 0
Do
count = st.Read(buf, 0, buf.Length)
fs.Write(buf, 0, count)
Loop While count <> 0
End Using
End Using
res.Close()
End Sub
End Class