识别文件/流的文件类型-VB.Net



当我从URL下载文件时遇到了问题(这不是我的主要问题(,问题随之而来。我从URL保存的文件可以是图像、文档、PDF或ZIP。

当路径没有扩展名时,是否存在某种方法来了解文件类型?或者从流中识别文件类型?

我正在使用Visual Studio 2010速成版-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

如果您正在使用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

对于图像,您可以将其加载到Image((对象中,并查看它是否抛出OutOfMemoryException——而不是图像。

PDF你可以读取它的前几个字节(PDF文件类型信息存储在那里,但目前不确定它到底是什么(。

ZIP和DOC我不确定。

如果您正在使用WebRequests,则可以获取响应流的内容类型。有关MIME/内容类型的详细信息,请点击此处:http://msdn.microsoft.com/en-us/library/ms775147.aspx

最新更新