0

当我从 URL 下载文件时遇到问题(这不是我的主要问题),然后问题就出现了。我从 URL 保存的文件可以是图像、文档、PDF 或 ZIP。

当路径没有扩展名时,是否存在一些知道文件类型的方法?或者从流中识别文件类型?

我正在使用 Visual Studio 2010 Express Edition - Framework.Net 3.5 - A Window App

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
4

2 回答 2

0

If you are using WebRequest for the download.

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

You can now have a routine to save the file using a particular extension depending on the content type. for instance a content type of "image/jpeg" can be saved as *.jpg

于 2013-02-24T00:53:33.510 回答
0

For an Image you can load it into an Image() object and see if it throws an OutOfMemoryException -- not an image.

PDF you can read the first few bytes of it (the PDF file type info is stored there, though not sure exactly what it is at the moment).

ZIP and DOC I'm not sure about.

If you are using WebRequests you can grab the content type of the response stream. More information about the MIME/content types here: http://msdn.microsoft.com/en-us/library/ms775147.aspx

于 2013-02-24T00:57:05.353 回答