当我从URL下载文件时遇到问题(这不是我的主要问题),问题出现之后。 我从URL保存的文件可以是图像,doc,PDF或ZIP。
当路径没有扩展名时,是否存在一些知道文件类型的方法? 或者从流中识别文件类型?
我正在使用Visual Studio 2010 Express Edition - Framework.Net 3.5 - 一个窗口应用程序
Public Function DownloadFile_FromURL(ByVal URL As String, ByVal DestinationPath As String) As Boolean
DownloadFile_FromURL = False
Try
Dim vRequest As Net.HttpWebRequest
Dim vResponse As Net.HttpWebResponse
vRequest = Net.WebRequest.Create(New Uri(URL))
vRequest.Method = "GET"
vRequest.AllowAutoRedirect = True
vRequest.UseDefaultCredentials = True
vResponse = vRequest.GetResponse
If vResponse.ContentLength <> -1 Then
Dim vLen As Long = vResponse.ContentLength
Dim vWriteStream As New IO.FileStream(DestinationPath, IO.FileMode.CreateNew)
Dim vStream As IO.Stream = vResponse.GetResponseStream()
Dim vReadBytes() As Byte = New Byte(255) {}
Dim vCount As Integer = vStream.Read(vReadBytes, 0, vReadBytes.Length)
While vCount > 0
vWriteStream.Write(vReadBytes, 0, vCount)
vCount = vStream.Read(vReadBytes, 0, vReadBytes.Length)
End While
vWriteStream.Flush() : vWriteStream.Close()
vResponse.Close() : vRequest = Nothing : GCcleaner()
Dim v = System.IO.Path.GetExtension(DestinationPath)
DownloadFile_FromURL = True
End If
Catch ex As Exception
Throw New Exception(ex.mc_GetAllExceptions)
End Try
End Function
答案 0 :(得分:0)
如果您使用WebRequest进行下载。
Dim uri As String = "http://domain.com/resource"
Dim request As HttpWebRequest = DirectCast(WebRequest.Create(uri), HttpWebRequest)
request.Method = "GET"
Dim response As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)
Dim contentType = response.ContentType
' this will have the content type/ file type
现在,您可以根据内容类型使用特定扩展名来保存文件。例如,内容类型“image / jpeg”可以保存为* .jpg
答案 1 :(得分:0)
对于Image,您可以将其加载到Image()对象中,看看它是否抛出OutOfMemoryException - 而不是图像。
PDF你可以读取它的前几个字节(PDF文件类型信息存储在那里,虽然不确定它到底是什么)。
ZIP和DOC我不确定。
如果您使用的是WebRequests,则可以获取响应流的内容类型。有关MIME /内容类型的更多信息,请访问:http://msdn.microsoft.com/en-us/library/ms775147.aspx