Search code examples
c#wpffilepathsoundplayer

C# SoundPlayer class isn't finding the file at the specified path


I'm using the Path.GetFullPath of the System.IO namespace and it is correctly pulling the absolute filepath for the sound file that I have stored in the program. It is displaying it in a MessageBox and the filepath is definitely correct. However, when I call that exact same filepath using SoundPlayer, it is saying that a sound file does not exist at that location. I see absolutely nothing wrong with my code.

error message

absolute filepath

where the file is stored in the solution explorer


Solution

  • Path.GetFullPath returns a completed path based on your partial path string and your current directory

    The current directory, if you start your compiled executable out of e.g. windows explorer, will be e.g. the bin/Debug your're double-clicking it from.

    If you start it from the Visual Studio debugger, the current path will be the solution or project directory (can't remember), by default anyway.

    So this scheme of obtaining the file path does not work, if you want to do both: sometimes start out of Visual Studio, and sometimes directly (e.g. if you copy the binaries to someone else to try our your cool program). Try the following:

    • in your solution directory, have a e.g. "data" folder besides the bin folder and your source files etc - assuming you use default layout of a folder called "bin", where the Debug and Release folders for the binaries are
    • use a reliable method to obtain the absolute path of your executable
    • use your knowledge of the directory structure to "pedal back" from the executable folder to the "data" folder, where your audio file can be in (either directly, or maybe in a "audio" subfolder?)

    That could look like this:

    using System.IO;
    // ...
    public static string GetExeDirSubPath(string subPath)
    {
        return new DirectoryInfo( Path.Combine( GetExeDirPath(), subPath ) ).FullName; // DI stripts dtuff  like "..\..\" and moves to the actual path
    }
    
    public static string GetExeDirPath()
    {
        System.Reflection.Assembly a = System.Reflection.Assembly.GetEntryAssembly();
        string baseDir = System.IO.Path.GetDirectoryName(a.Location);
        return baseDir;
    }
    

    Then, assuming the above laid out directory structure, you would get the full path to an audio file:

    // first "..": go from Debug or Release folder of your exe to bin
    // second "..": go from bin to the folder containing both: bin and data folders
    var fullpath = GetExeDirSubPath( "../../data/audio/silly_sound.wav" );