Link to home
Start Free TrialLog in
Avatar of Murray Brown
Murray BrownFlag for United Kingdom of Great Britain and Northern Ireland

asked on

ASP.net VB.net check if a file is a valid pdf

Hi

In ASP.net what code would I use to check if a certain file is a pdf. I want to add this check to the following code

    Protected Sub btnView_Click(sender As Object, e As EventArgs) Handles btnView.Click
        Try
            Dim oSelectedFile As String
            If Me.ListBox1.SelectedItem.Text <> "" Then
                oSelectedFile = Me.ListBox1.SelectedItem.Text
            Else
                Exit Sub
            End If
            'Response.Clear()
            'Dim filePath As String = "~/Uploads/" & oSelectedFile
            'Response.ContentType = "application/pdf"
            'Response.WriteFile(filePath)
            'Response.TransmitFile(filePath)

            'Dim FilePath As String = Server.MapPath("piyushsir.pdf")
            Dim FilePath As String = Server.MapPath("~/Uploads/" & oSelectedFile)
            Dim User As New System.Net.WebClient()
            Dim FileBuffer As [Byte]() = User.DownloadData(FilePath)
            If FileBuffer IsNot Nothing Then
                Response.ContentType = "application/pdf"
                Response.AddHeader("content-length", FileBuffer.Length.ToString())
                Response.BinaryWrite(FileBuffer)
            End If

        Catch ex As Exception
            'Response.Write(ex.Message)
            Me.lblErrorDeleting.Text = ex.Message & " hr556"
        End Try
    End Sub

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Norie
Norie

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Murray Brown

ASKER

Thanks
Hi Murray,

I am not sure how this happened but I put in 3 possible ways to solve this. Somehow that comment never made it.
1. Check file extension and see if it is pdf or not. - Easiest but not reliable.
2. Read header bytes and figure out if the file is a PDF or an image - might not be as accurate as other methods.
3. Check if it is pdf using any PDF library and if it is not, check if it is a valid image and proceed accordingly - Hardest but most accurate.

Hope this helps.

Regards,
Chinmay.
Thanks. I still don't know how to best view the image. Should I use an image control and just set the Image ImageUrl to this or is there a better way?
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial