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,

Thanks,
Rocco

Dani AI

Generated

Good call not trusting the file extension, . A quick, extension-agnostic check is to verify the RIFF/WAVE signature bytes. A valid WAV starts with ASCII "RIFF", a 32-bit size, then "WAVE". Here is a tiny helper that only reads the first 12 bytes:

public static bool IsWavFile(string path)
{
    using (var fs = File.OpenRead(path))
    {
        if (fs.Length < 12) return false;
        var header = new byte[12];
        if (fs.Read(header, 0, header.Length) != header.Length) return false;

        bool riff = header[0]=='R' && header[1]=='I' && header[2]=='F' && header[3]=='F';
        bool wave = header[8]=='W' && header[9]=='A' && header[10]=='V' && header[11]=='E';
        return riff && wave;
    }
}

For a stricter validation, parse chunks and ensure a mandatory "fmt " chunk exists (and typically "data" follows). Those chunk IDs are part of the RIFF/WAVE spec. (learn.microsoft.com)

Building on ’s approach: if you do MIME sniffing via FindMimeFromData, remember Windows’ detector only looks at the first ~256 bytes and may return different but equivalent types across environments. Treat audio/wav, audio/wave, and audio/x-wav (and sometimes audio/vnd.wave) as WAV to avoid false negatives. (learn.microsoft.com)

If you want a full parse (and to read format details like sample rate/bit depth), use a library instead of rolling your own. For example, NAudio’s WaveFileReader will open genuine WAV files and throw if the RIFF/WAVE structure is not valid, which doubles as a robust validation step before you proceed. (github.com)

Recommended Answers

All 2 Replies

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
http://stackoverflow.com/questions/58510/in-c-how-can-you-find-the-mime-type-of-a-file-based-on-the-file-signature-not-th

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);
                else
                    fs.Read(buffer, 0, (int)fs.Length);
            }
            try
            {
                System.UInt32 mimetype;
                FindMimeFromData(0, null, buffer, 256, null, 0, out mimetype, 0);
                System.IntPtr mimeTypePtr = new IntPtr(mimetype);
                string mime = Marshal.PtrToStringUni(mimeTypePtr);
                Marshal.FreeCoTaskMem(mimeTypePtr);
                return mime;
            }
            catch (Exception e)
            {
                return "unknown/unknown";
            }
        }

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


    }
}
commented: Great! +6
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.