Search code examples
c#file-type

When checking if a file is MP3 is checking the filename string with an .EndsWith good enough?


I'm doing this:

    private void LoadSoundFile()
    {
        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            if (openFileDialog1.FileName.EndsWith(".mp3"))
            {
                txtFileName.Text = openFileDialog1.FileName;
            }
            else
            {
                MessageBox.Show("Currently Musicality only supports MP3 files.", "Unsupported file chosen.");                        
            }
        }

    }

Is there a better way of checking file types or am I doing it the right way?


Solution

  • Having the .mp3 extension doesn't mean it is an mp3, but not having it is an (acceptable) indication that it isn't.

    At some point you will call some API to play the file, and it will fail. When it does, you know it's not a playable file. So make sure you handle that with some decent UI too.