Hi Sumeet,
For verifying the file extension with magical numbers you need to do workaround.
I have created a sample which full fill your requirement you need to modify the according to your need.
HTML
<div>
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td>
<asp:FileUpload ID="fileUpload" runat="server" />
</td>
</tr>
<tr>
<td>
<asp:Button ID="Button1" Text="Submit" OnClick="Save" runat="server" />
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblMessage" runat="server" />
</td>
</tr>
</table>
</div>
C#
protected void Save(object sender, EventArgs e)
{
string filePath = fileUpload.PostedFile.FileName;
string filename = Path.GetFileName(filePath);
string ext = Path.GetExtension(filename);
string contenttype = String.Empty;
Stream checkStream = fileUpload.PostedFile.InputStream;
BinaryReader chkBinary = new BinaryReader(checkStream);
Byte[] chkbytes = chkBinary.ReadBytes(0x10);
string data_as_hex = BitConverter.ToString(chkbytes);
string magicCheck = data_as_hex.Substring(0, 11);
//Set the contenttype based on File Extension
switch (magicCheck)
{
case "FF-D8-FF-E1":
contenttype = "image/jpg";
break;
case "FF-D8-FF-E0":
contenttype = "image/jpeg";
break;
case "25-50-44-46":
contenttype = "text/pdf";
break;
}
if (contenttype != String.Empty)
{
Byte[] bytes = chkBinary.ReadBytes((Int32)checkStream.Length);
lblMessage.Text = "Uploaded File is of type " + contenttype;
lblMessage.ForeColor = System.Drawing.Color.Green;
}
else
{
lblMessage.Text = "Please Upload Valid File with Original extension";
lblMessage.ForeColor = System.Drawing.Color.Red;
}
}
VB.Net
Protected Sub Save(sender As Object, e As EventArgs)
Dim filePath As String = fileUpload.PostedFile.FileName
Dim filename As String = Path.GetFileName(filePath)
Dim ext As String = Path.GetExtension(filename)
Dim contenttype As String = [String].Empty
Dim checkStream As Stream = fileUpload.PostedFile.InputStream
Dim chkBinary As New BinaryReader(checkStream)
Dim chkbytes As [Byte]() = chkBinary.ReadBytes(&H10)
Dim data_as_hex As String = BitConverter.ToString(chkbytes)
Dim magicCheck As String = data_as_hex.Substring(0, 11)
'Set the contenttype based on File Extension
Select Case magicCheck
Case "FF-D8-FF-E1"
contenttype = "image/jpg"
Exit Select
Case "FF-D8-FF-E0"
contenttype = "image/jpeg"
Exit Select
Case "25-50-44-46"
contenttype = "text/pdf"
Exit Select
End Select
If contenttype <> [String].Empty Then
Dim bytes As [Byte]() = chkBinary.ReadBytes(DirectCast(checkStream.Length, Long))
lblMessage.Text = Convert.ToString("Uploaded File is of type ") & contenttype
lblMessage.ForeColor = System.Drawing.Color.Green
Else
lblMessage.Text = "Please Upload Valid File with Original extension"
lblMessage.ForeColor = System.Drawing.Color.Red
End If
End Sub
ScreenShot
