Is it possible to verify that a posted file is pdf or not?

asp.net, c#, pdf

Solution

As all PDF files start with the ASCII string "%PDF-", simply test the first few bytes of the file to ensure that they start with this string.

bool IsPdf(string path)
{
    var pdfString = "%PDF-";
    var pdfBytes = Encoding.ASCII.GetBytes(pdfString);
    var len = pdfBytes.Length;
    var buf = new byte[len];
    var remaining = len;
    var pos = 0;
    using(var f = File.OpenRead(path))
    {
        while(remaining > 0)
        {
            var amtRead = f.Read(buf, pos, remaining);
            if(amtRead == 0) return false;
            remaining -= amtRead;
            pos += amtRead;
        }
    }
    return pdfBytes.SequenceEqual(buf);
}

Problem

The conserned website primary work is to accept files from users and save it. Every thing was fine till 2 months back when i was told to enforce a constraint to accept only pdf files. Before that users were in the habit of submitting various formats from text,rtf to good pdf. I applied the constraint by checking the file extention --simple right?? however when the admin checked those files some good 60% of the files were corrupt. I spent many sleepless nights to determine the cause of curruption then suddenly i thought may be they are submitting corrupt files. I took the previous records and determined the favourite format of file type of some users from whome we were getting corrupt files. I changed the extention back to there favourite extention and boom.. the file opened. what I came to know however dispite telling in bold to user how to convet there files to pdf some(many) were just changing the extention and submitting. Since the website rewards the users on no. of file submitted administration people are grunting at me. Is there any way i can check the file is pdf or not without relying on the extention?? I am using fileupload in c# 3.5 asp.net

Original source

Related problems