C#SoundPlayer类在指定路径下找不到文件

时间:2019-10-14 18:18:45

标签: c# wpf filepath soundplayer

我正在使用System.IO命名空间的Path.GetFullPath,它正在正确提取我存储在程序中的声音文件的绝对文件路径。它在MessageBox中显示它,并且文件路径绝对正确。但是,当我使用SoundPlayer调用完全相同的文件路径时,就是说该位置不存在声音文件。我的代码绝对没错。

error message

absolute filepath

where the file is stored in the solution explorer

1 个答案:

答案 0 :(得分:1)

Path.GetFullPath根据您的部分路径字符串和当前目录

返回完整的路径

当前目录,如果您从其他位置启动已编译的可执行文件Windows资源管理器,例如bin / Debug,双击它。

如果从Visual Studio调试器启动它,则默认情况下,当前路径将是解决方案或项目目录(不记得了)。

因此,如果您想同时执行以下两种操作,则无法使用这种获取文件路径的方案:有时是从Visual Studio开始,有时是直接启动(例如,如果将二进制文件复制到其他人来尝试我们很酷的程序)。 请尝试以下操作:

  • 在您的解决方案目录中,例如“数据”文件夹 bin文件夹和您的源文件等-假设您使用名为“ bin”的文件夹的默认布局,其中二进制文件的Debug和Release文件夹位于
  • 使用可靠的方法获取可执行文件的绝对路径
  • 利用您对目录结构的了解,从可执行文件文件夹“回踩”到“数据”文件夹,您的音频文件可以位于该文件夹中(直接位于还是位于“音频”子文件夹中?)

可能看起来像这样:

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;
}

然后,假设采用上面列出的目录结构,您将获得音频文件的完整路径:

// 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" );