Hi guys:

Let's say somebody may change the extension of a .doc or .mp3 file to .wav, in my application, I want to check to make sure if a file is actually a .wav file.

How do I do this in C# ?

Please let me know,


What you want to do here is check the "MIME" type of the file. This is saved into the file in the header. Internet explorer does this to know what to do with a file, and Windows media player does this to know what code to use to render a file. Ever get the "file has a incorrect extention windows media player can attempt to play the file anyway" dialog? lol

Here is an example of doing so using the same lib that IE uses

Feel free to google around for more exact solutions. there are quite a few.

And just for fun I modified some code from that link and here is a class that you can simply call the "isWave" method and it will return true/false :)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.IO;

namespace CheckMimeForWav
    class MimeCheck

        [DllImport(@"urlmon.dll", CharSet = CharSet.Auto)]
        private extern static System.UInt32 FindMimeFromData(
            System.UInt32 pBC,
            [MarshalAs(UnmanagedType.LPStr)] System.String pwzUrl,
            [MarshalAs(UnmanagedType.LPArray)] byte[] pBuffer,
            System.UInt32 cbSize,
            [MarshalAs(UnmanagedType.LPStr)] System.String pwzMimeProposed,
            System.UInt32 dwMimeFlags,
            out System.UInt32 ppwzMimeOut,
            System.UInt32 dwReserverd

        public string getMimeFromFile(string filename)
            if (!File.Exists(filename))
                throw new FileNotFoundException(filename + " not found");

            byte[] buffer = new byte[256];
            using (FileStream fs = new FileStream(filename, FileMode.Open))
                if (fs.Length >= 256)
                    fs.Read(buffer, 0, 256);
                    fs.Read(buffer, 0, (int)fs.Length);
                System.UInt32 mimetype;
                FindMimeFromData(0, null, buffer, 256, null, 0, out mimetype, 0);
                System.IntPtr mimeTypePtr = new IntPtr(mimetype);
                string mime = Marshal.PtrToStringUni(mimeTypePtr);
                return mime;
            catch (Exception e)
                return "unknown/unknown";

        public bool isWave(string FileName)
            if ("audio/wav" == getMimeFromFile(FileName))
                return true;
                return false;

commented: Great! +6