user2650277
user2650277

Reputation: 6749

Checking file extension in asp.net

I am trying to check the file extension but for some reason Valid is always false.

 <asp:FileUpload ID="LogoUpload" CssClass="form-control" runat="server" /><asp:Button ID="BtnLogoUpload" runat="server" CssClass="btn btn-primary" Text="Upload" />
                 <asp:Label ID="lblLUploadMessage" runat="server"  ForeColor="Red" ></asp:Label>

Protected Sub BtnLogoUpload_Click(sender As Object, e As EventArgs) Handles BtnLogoUpload.Click
        If (LogoUpload.HasFile) Then
            Dim fileExtension As String = Path.GetExtension(LogoUpload.FileName)
            Dim extension = New String() {"jpg", "png", "gif"}
            Dim Valid As Boolean = False
            For Each ext As String In extension
                If ext.Equals(fileExtension) Then
                    Valid = True
                End If
            Next
            If Valid = True Then
                LogoUpload.SaveAs(Server.MapPath(String.Format("{0}/{1}/{2}", "~/CW/uploads", register_username.Text, "logo") + LogoUpload.FileName)) ' Save file in directory
                lblLUploadMessage.Text = "File Uploaded Successfully"
                lblLUploadMessage.ForeColor = System.Drawing.Color.Green
            Else
                lblLUploadMessage.Text = "File extension is not valid"

            End If
        End If
    End Sub

I am always getting File extension is not valid

Upvotes: 0

Views: 2453

Answers (1)

krivtom
krivtom

Reputation: 24916

Method Path.GetExtension has a catch. As described in MSDN documentation, the return value of this method is:

The extension of the specified path (including the period "."), or null, or String.Empty.

The important part here is (including the period "."). This means that if you upload the bmp file, method Path.GetExtension returns not bmp, but .bmp.

So in order to make it work you have to use extensions with periods:

Dim extension = New String() {".jpg", ".png", ".gif"}

or trim period from the start of extension before making your checks:

Dim fileExtension As String = Path.GetExtension(LogoUpload.FileName)
fileExtension = fileExtension.TrimStart("."c)

Upvotes: 1

Related Questions